0

I ma really new to javascript but I am using jquery and the jquery cookie library. I was wondering how I can put the contents of an input text box into a cookie.

This is the code I have tried but it hasn't worked:

JS

$.cookie("location_input", "#lat");

HTML

<input id="loc" placeholder="Location" type="text"></input>

Is there something else stopping this from working or have I not done this bit of code correctly?

3 Answers 3

4

Your HTML is this:

<input id="loc" placeholder="Location" type="text"></input>

In order to get the contents of an input text box, you should simply do this:

var data = $("#loc").val(); 

and to set this data into a cookie, you need to do this:

$.cookie("location_input", data);

I hope, this makes things clear as why your code didn't worked :)

Sign up to request clarification or add additional context in comments.

Comments

3

try this

document.cookie = "location_input="+$("#loc").val();

Using #loc, since it is the id of your input. $.cookie is useful when retrieving the cookie, not nessecary when saving.

3 Comments

But if you're going to use it to retrieve the cookie value, might as well use it to set it too? ;)
Maybe I am lazy, or victim of old habits. I use $.cookie too, but when I save cookies, I'm using document.cookie. Uses $.cookie more as a "getter".
Fair enough, I like to keep both at the same level of abstraction for others in the future. I think it would be confusing to see the cookie set in one way and read in another. Good suggestion though, it's worth pointing out :)
2

You need something like:

$.cookie("location_input", $("#lat").val());

At the moment you are setting the cookie to the string value #lat, not actual value of the input.

Also I think your example has a typo, #lat instead of #loc :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.