Home » JavaScript Cookie with multiple Name

JavaScript Cookie with multiple Name

by Online Tutorials Library

Cookie with multiple Name-Value pairs

In JavaScript, a cookie can contain only a single name-value pair. However, to store more than one name-value pair, we can use the following approach: –

  • Serialize the custom object in a JSON string, parse it and then store in a cookie.
  • For each name-value pair, use a separate cookie.

Examples to Store Name-Value pair in a Cookie

Example 1

Let’s see an example to check whether a cookie contains more than one name-value pair.

Output:

Test it Now JavaScript Cookie with multiple Name

On clicking Get Cookie button, the below dialog box appears.

JavaScript Cookie with multiple Name

Here, we can see that only a single name-value is displayed.

However, if you click, Get Cookie without filling the form, the below dialog box appears.

JavaScript Cookie with multiple Name

Example 2

Let’s see an example to store different name-value pairs in a cookie using JSON.

Test it Now

Output:

JavaScript Cookie with multiple Name

On clicking Get Cookie button, the below dialog box appears.

JavaScript Cookie with multiple Name

Here, we can see that all the stored name-value pairs are displayed.

Example 3

Let’s see an example to store each name-value pair in a different cookie.

Output:

Test it Now JavaScript Cookie with multiple Name

On clicking Get Cookie button, the below dialog box appears.

JavaScript Cookie with multiple Name

Here, also we can see that all the stored name-value pairs are displayed.

Next TopicDeleting Cookies

You may also like