Michael Falciglia
Michael Falciglia

Reputation: 1046

How to set a input value of a form with jQuery Cookie

Hi I am learning jQuery and right now I am trying to use jQuery Cookie to set a form input value.

I have been able to set the cookie from a form using this:

<script>
  $(document).ready(function () {
    $("#saveForm").click(function() {
      $.cookie('myCookie', $("#element_1").val(), { expires: 365 });
    });
  });
</script>

I was able to verify the cookie using an alert like this:

<script>
  alert( $.cookie("myCookie") );
</script>

But after searching numerous posts on here, I was not able to find the same question and I have looked at numerous tutorials and can't find the code to set the value of a input field in a form. Thanks in Advance!!

Upvotes: 2

Views: 4323

Answers (2)

fanfavorite
fanfavorite

Reputation: 5199

You could do something as simple as:

$(document).ready(function () {
   $("#saveForm").click(function() {
      $.cookie('myCookie', $("#element_1").val(), { expires: 365 });
   });
   $("#element_1").val($.cookie('myCookie'));
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

in the dom ready handler set the value using .val()

$(document).ready(function () {
    $("#saveForm").click(function () {
        $.cookie('myCookie', $el1.val(), {
            expires: 365
        });
    });

    //set the value of the cookie to the element element_1
    var $el1 = $("#element_1").val($.cookie("myCookie"))
});

Upvotes: 5

Related Questions