Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no.

<input type="button" name="yes" onclick="button()">
<input type="button" name="no">

In order to enhance user experience, I am looking to implement a feature that will create a cookie named "YES" when the yes button is clicked. This cookie should persist for 7 days before expiring. How can I accomplish this task with the unique requirement of only storing the value "YES" within the cookie?

Answer №1

If you want to manage cookies in JavaScript, one option is using the document.cookie method:

var expDate = new Date();
expDate.setDate(expDate.getDate() + 7);
document.cookie = 'your_cookie_name=YES;expires=' + expDate.toUTCString();

Alternatively, if you prefer using jQuery, you can explore the functionalities of the Cookie plugin. Check out this helpful example.

Answer №2

Here is the method I use:

var cookieHandler = {
    "create": function(cookieName, value, daysToExpire) {
        if (typeof daysToExpire !== 'number' || typeof cookieName !== 'string' || typeof value !== 'string') {
            return false;
        }
        var expirationDate = new Date();
        expirationDate.setTime(expirationDate.getTime() + (daysToExpire*86400000));
        document.cookie = cookieName + '=' + value + '; expires=' + expirationDate.toGMTString() + '; path=/';
    },
    "read": function(cookieName) {
        var allCookies = document.cookie,
            index, val = false;
        allCookies = allCookies.split(';');
        for (index = 0; index < allCookies.length; index++) {
            if (allCookies[index].indexOf(cookieName) !== -1) {
                while (allCookies[index].indexOf(cookieName) > 0 && allCookies[index].length > cookieName.length) {
                    allCookies[index] = allCookies[index].substr(1);
                }
                val = allCookies[index].substr(cookieName.length + 1);
            }
        }
        return val;
    },
    "erase": function(cookieName) {
        this.create(cookieName, '', -1);
    }
};

You can then use these methods:

cookieHandler.create("userName", "Bill", 7); // store userName "Bill" for 7 days.

cookieHandler.read("userName"); // "Bill"

cookieHandler.erase("userName"); 

Check out this code in action by visiting: http://jsfiddle.net/robert/4vLT6/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to access property 'map' of undefined - error occurred while processing JSON data in line test.js:11

I'm attempting to utilize the json file in the test component below, but I keep encountering the error: TypeError: Cannot read property 'map' of undefined. I have modified the file within the test.js component, and when testing it with a sa ...

Using JQuery to create an animated slideToggle effect for a multicolumn list

I have a large list where each li element has a width of 33%, resulting in 3 columns: computers monitors hi-fi sex-toys pancakes scissors Each column contains a hidden UL, which is revealed through slideToggle on click. JQuery $('.subCate ...

creating a personalized CSS style rule

Can a custom rule be created in CSS using @media for a parent class to make changes based on the class? <div class="parentGreen"> <ul class="ul1"> <li>1</li> <li>2</li> &l ...

Processing the results from a recursive function call in Node.js

I have an objects array that needs to be processed with delayed calls to an external server, then collect all results into an array for postprocessing. Here is an example: (async () => { const serverOperation = () => new Promise(resolve => setT ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Is it necessary to confirm the validity of url.format(urlObject)?

I have been exploring the NodeJS URL API and am particularly interested in the url.format(urlObject) method. My goal is to develop a function that first validates the urlObject before using the format function, and throws a TypeError if any of the key/valu ...

What is the best way to retrieve state within a property of a React class component?

I have encountered an issue with a React Class Component where I am trying to separate a part of the rendered JSX but unable to access the Component's state within the separated JSX as a property of the class. The scenario is quite similar to the fol ...

Use the regex tag in a React component to find a specific tag by name within two different possible

Looking for a regex that can identify <Field ...name="document"> or <FieldArray ...name="document"> within a multiline text string so they can be replaced with an empty string. The text string is not formatted as HTML or XHTML, it simply conta ...

Which option's value was recently removed from the fetch command?

I created a function to handle duplicate selections in a select element. It is functioning properly, but I noticed that when I remove an option from the select, my array remains unchanged. If I remove an option, I want my code to detect the value of that ...

Tips on displaying each element of an array in a unique format within a React component

I am working on creating a component that will display data in boxes. Each set of constant data should be placed within a div for organization. Currently, I have a Box component that is responsible for displaying the data. The Tutorial component receives ...

React window resizing actionsWould you like some more information on this

I am attempting to create a resize function that will retrieve the window width and dynamically display it using react. Here is my current code: class Welcome extends React.Component { constructor() { super(); this.state = { ...

Error when using jQuery AJAX to parse JSONP callback

Take a look at this code snippet: $(function () { $.ajax({ type: "GET", url: "http://mosaicco.force.com/siteforce/activeretailaccounts", dataType: "jsonp", crossDomain: true, jsonp: "callback", error: f ...

Methods for retrieving and persisting the data from a particular row within a table using JavaScript or jQuery

Is there a way to store the selected row values of a table in an array of arrays using JavaScript / jQuery? Check out this JSFiddle I believe that we should listen for the event when the 'Show selected' button is clicked. For instance, in Java ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

Unexpected symbol in JSON parsing with JavaScript

let information; $.ajax({ url: link, type: 'POST', dataType: "json", success: function (data, textStatus) { information = data; alert(data.name); } }); I am attempting to retrieve JSON-encoded data from a spe ...

Determining if a path is within the same directory: a step-by-step guide

I need to check if the input path is located in the same folder or not Question: Is the input path in the same folder? For example, if my current path is f://learning/java and I am currently in a folder named java, then any path that directly belongs to ...

Notifying the view with a SignalR message from the controller upon event trigger

Just starting out with SignalR and attempting to set up a notification for a specific event triggered by an API. What I've attempted: Hub: public class NotificationHub : Hub { private static IHubContext hubContext = GlobalHost.Connectio ...

Employing ajax.actionlink in mvc4 results in a page refresh

I am working on a view that looks like this: @model IEnumerable<DomainClasses.Class> @{ ViewBag.Title = "لیست "; } <div id="test"> <h2>لیست کلاس ها</h2> <p> @Html.ActionLink("ایجاد کلاس جدی ...

Guide on developing a JavaScript script for implementing across numerous Bootstrap modals within a single webpage

I have been working on setting up a page with 14 different modals. Initially, all the modals were opening normally, but I recently discovered a way to make them draggable when opened. After some trial and error, I managed to implement this feature successf ...

Move the Form to the Top of the Window and Highlight the First Input Field

There's a link in the header that says "Let's chat": <div class="letstalk"> <a href="javascript:scrollForm();"> Let's chat <img src="/wp-content/uploads/link-icon.png"> </a> </div> ...