i want to take text from <li> selected from user as cookie value..
but help me to set Var selected as cookie value
please suggest correction in this code

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jcookie.js"></script>

<script type="text/javascript">
$(document).ready(function(){	
$("li").click(function() {
        var selected = $(this).html();
	});

$.cookie("selection",selected);
alert($.cookie("example"));
});
</script>
<ul> select type
<li> left hand</li>
<li> right hand</li>
</ul>

Dani AI

Generated

The problem is a timing/scope issue: the selected value is created inside the click handler but your cookie-write runs outside of it, so nothing is set when the page loads. was right to suggest moving the cookie write into the click handler. Also confirm the cookie library is loaded after jQuery and before your script, and that you read the same cookie name you write.

A cleaner, modern approach is to use a current cookie library (for example js-cookie) and set the cookie when the user clicks. Use .text() (not .html()) to capture plain text, trim whitespace, and give the cookie an expiration and path so it behaves predictably across pages:

$(function(){
  $("ul").on("click", "li", function(){
    var value = $(this).text().trim();
    Cookies.set("selection", value, { expires: 7, path: "/" });
    alert(Cookies.get("selection"));
  });
});

Troubleshooting tips: check browser devtools (Application/Storage -> Cookies) to confirm the cookie, use console.log instead of alerts during development, and verify script load order (jQuery first, cookie lib second, your script third). If list items are added dynamically, use event delegation as shown. For non-sensitive client-side state consider localStorage (simpler API, larger quota). Do not store sensitive authentication data in client-side cookies; use server-side sessions or secure tokens instead.

This addresses the scope/timing bug in the original post and gives a robust, maintainable pattern for storing the chosen LI text as a cookie. , moving the set/read into the click handler as shown will fix the immediate issue.

Recommended Answers

All 2 Replies

Put lines 10&11 after line 7.

thanx friend..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.