I want to load a cookie value directly to all html field with an specific class when the page is loaded. I have a cookie created with the same name as the field’s id.
Doing this does not work.
$(".class").val(function(){
el=$(this);
id=el.attr("id");
cookie_val=$.cookie(id);
el.val(cookie_val);
});
Any idea?
When passing a function to jQuery’s
.val()method, the desired value should be returned by the function.As your code stands, your function is being run which does set the value. It then returns
undefined, however, which sets it to empty.This should work:
Alternatively, you could use
.each()to have your function do the value setting without needing to return:FWIW, I wrote a cookies library which provides jQuery plugins for this very functionality (fill a field with the value held by a cookie of the same name).