Create a cookie in javascript

There seems to be an issue with this code snippet:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
var username=getCookie("username");
if (username=="username"){
    document.getElementById(mydivx).style.display = 'block';  }else{
    document.getElementById(mydivx).style.display = 'none'; 
  }
}

There's also a button included to define the cookie:

<a href="#" onClick="setCookie('username',username,365); return true">hide</a>

The expected behavior is that when the button is clicked, it sets a cookie named "username" with the value "username", and then retrieves and displays the cookie using the getcookie function.

Can you spot any mistakes in my implementation?

Any assistance would be greatly appreciated!

UPDATE: ISSUE RESOLVED:

To fix the problem, simply remove the ";" from the function call, and ensure to use single quotes in the button code:

hide

Special thanks to stealthyninja for the solution!

Answer №1

To update your HTML code, make the following change:

<a href="#" onClick="setCookie('username', 'username', 365); return false">esconder</a>

It is important to include the return false so that clicking on the link does not trigger the browser to navigate to the specified href, resulting in a hash symbol (#) being displayed in the address bar. Essentially, this prevents the default action of the link click without requiring JavaScript for prevention.


Note:
Ensure that the second occurrence of username is either a variable or a string, as using it by itself will result in an undefined value.

Answer №2

It seems like your setcookie function was never called. You can try the following solution:

<a href="#" onClick="setCookie('username', username, 365); return true">hide</a>

Answer №3

<a href="#" onClick="createCookie('username', username, 365); return true">hide</a>

There seems to be an issue in that code. The onClick attribute and 'username' are not formatted correctly. You should try:

<a href="#" onClick="createCookie('username', 'username', 365);">hide</a>

Answer №4

It seems like this might not be the complete solution, but pay attention to this particular line:

<a href="#" onClick="setCookie("username",username,365); return true">esconder</a>

There is an issue here because you are prematurely ending the string by using double quotes within double quotes; consider trying

<a href="#" onClick="setCookie('username',username,365); return true">esconder</a>

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

A CSS rule to display a nested list on the left-hand side

I created a menu that you can view here. When hovering over "tanfa demo example," the sublist appears on the right side. The issue I'm facing is that my menu is positioned all the way to the right, which means the sublist also appears on the extreme ...

How can I pass an object into EJS templates from views in Express 3.x?

Currently, I am utilizing ejs templates in combination with node.js and express 3.x. Is there a way to display the data object that is passed into the view? Can it be achieved similar to this example in index.ejs: <%= dump(session) %> ...

The mouse scurries away once the div height has been adjusted

How can I make the height of #header change when hovering over #hoverme, and then revert back to its original height when the mouse leaves #hoverme? If anyone knows a solution, please check out my jsfiddle as it's not working as I intended. Here is ...

What is the best way to trigger a refresh in Next.js React component?

Current Tech Stack Versions Next.js : 14.0.3 React : 18.0.2 // TestClientComponent.tsx "use client"; import { IResident } from "@interface/resident.types"; import { getResidents } from "@models/resident.service"; import { So ...

What could be the reason for the failure of the async await implementation in this particular code sample?

While attempting to follow a tutorial on YouTube, I encountered an issue where the code didn't work as expected. Can anyone lend a hand in helping me figure out what might be going wrong? let posts = [ {name: '1', data: 'Hi1'}, ...

Switching the website address after picking an option from the drop-down menu

I have an HTML form that includes two dropdown menus. The first dropdown is populated from a database using PHP, and the second dropdown is linked to the first one and uses AJAX to update its values based on the selection from the first dropdown. My goal ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Discovering specific keywords within HTML tags and performing replacements using jQuery

I am searching for specific strings within my HTML code, and if I find them, I want to replace them with nothing. For example: HTML: <img src=`javascript:alert("hello ,world!")`> My goal is to locate keywords like javascript, alert, etc, within H ...

Is there a way to achieve the same task with Ajax?

Hey there, I am new to the world of JavaScript and AJAX. I have been reading about how to convert a client-side JavaScript variable into a server-side PHP variable by using AJAX. Can someone please provide me with a code snippet using AJAX for this purpose ...

Iframe Loading at Lightning Speed

I have set up a script to load my iframe, but I noticed that the script loads the iframe content too quickly. Is there a way for me to configure it to preload all CSS images and content in the background before showing the full iframe content? Here is my ...

Send JSON data that has been refined utilizing jQuery

I am attempting to create a filtered JSON response using jQuery following a successful GET request of the original JSON response. The initial JSON response is an array of products from our Shopify store for the specific collection page the user is viewing. ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

Tips on activating the CSS style while typing using the onChange event in React

Is it possible to dynamically adjust the width of an input as we type in React? Currently, my input has a default width of 1ch. I would like it to increase or decrease based on the number of characters entered, so that the percentage sign stays at the end ...

vm.property compared to this.property

Although it may seem like a simple question, I am in need of some clarification. Currently, I have vuejs running on a single page of my website. The vm app is running in the footer script of the page without utilizing an app.js file or templates/components ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

Menu options

I am currently working on developing a mouseover navigation website. Initially, my design included main buttons for "Our Team", Locations, and Patient Resources. Here is the basic structure I had before attempting to switch to a mouseover approach... &l ...

There appears to be an inexplicable issue hindering the functionality of smoothscroll in

Continuing to improve my website: I have implemented a button for scrolling down the page, but I would like to add smooth scrolling functionality for a better user experience. After some research and experimentation, I came across this compact script tha ...

Is it possible to retrieve the IMEI number of a mobile phone using expo?

Currently working on developing a mobile app with React Native using Expo. I need to figure out a way to access the client's mobile IMEI number and display it in the front end of the app. Unsure of how to accomplish this task. Is there a method to do ...