How to use JavaScript to set and manipulate cookies with expiration dates based on user preferences?

To use JavaScript to set and manipulate cookies with expiration dates based on user preferences, you can follow these steps:

  1. Set a cookie with an expiration date:

    function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + value + expires + "; path=/"; }
  2. Retrieve a cookie by its name:

    function getCookie(name) { var nameEQ = name + "="; var cookies = document.cookie.split(';'); for(var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; while (cookie.charAt(0) === ' ') { cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(nameEQ) === 0) { return cookie.substring(nameEQ.length, cookie.length); } } return null; }
  3. Delete a cookie by setting its expiration date to a past date:

    function deleteCookie(name) { document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; }
  4. Let's say you have a preference form where the user can set the cookie expiration date. You can listen for form submission and use these functions accordingly:

    // Assumed form HTML structure: // <form id="preferenceForm"> // <label for="expirationDays">Expiration Days:</label> // <input type="number" id="expirationDays" name="expirationDays"> // <button type="submit">Save Preferences</button> // </form> var form = document.getElementById("preferenceForm"); form.addEventListener("submit", function(event) { event.preventDefault(); var expirationDays = parseInt(document.getElementById("expirationDays").value); if (expirationDays > 0) { setCookie("preference", "value", expirationDays); alert("Cookie set!"); } else { deleteCookie("preference"); alert("Cookie deleted!"); } });

This code listens for the form submission, retrieves the value entered in the input field, and based on that value, either sets a cookie with the specified expiration date or deletes the cookie by setting an expiration date in the past.