jayAnn jayAnn - 2 years ago 123
Javascript Question

how to display the set cookie to another html page on submit

im practicing on creating a html using jquery cookies. i already know how to set, get, and delete cookies. one thing i don't know is how to display the set cookies on the next page.
i have this html ccodes:

<FORM id = 'login' meth0d = 'post' action = 'Coutput.html' >
<input id = 'name' type = "text" value = ''>
<input id="btnSet" type="submit" value="Go"/>
<input id="btndelete" type="button" value="delete cookie"/>
</form>


and i have this javascript code:

$('form#login :submit').addClass('inputSubmitBtn').click(function(){
if($('#name').val() == "" ){
$("#name").focus();
alert('please input name');
return false;
}
else{
$.cookie("cookie_name", null);
$.cookie('cookie_name', $('#name').val());
alert('new cookie name' +$('#name').val()));
$('#name').append($.cookie('cookie_name'));
};
});


questions:


  1. why is it that everytime i used
    $.cookie('cookie_name', $('#name').val(), { expires: null, path: '/', domain: 'cegi1.html', secure: true });
    , my cookie os always set to null, though i set another one, it always returns null?

  2. how can i display my newly set cookie in Coutput.html? (ex. name = luke, output in Coutput.html must be "welcome luke")



thanks for reading. please help..

Answer Source

It seems that <input id="btnSet" type="submit" value="Go"/> is submitting form to the other page before evaluating $('form#login :submit').click(function(). And also you have got error on alert('new cookie name' +$('#name').val()));. This should work.

<script src="jquery.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$(function ()
{
    $("#btnSet").click(function(){
       if($('#name').val() == "" ){         
          $("#name").focus();
          alert('please input name');
          return false;
       }
       else{
          $.cookie("cookie_name", null);
          $.cookie('cookie_name', $('#name').val());
          alert('new cookie name' +$('#name').val());
          $('#name').append($.cookie('cookie_name'));
       };           
        window.location = $(this).parent('form').attr("action");
    });
})

</script>

 <form id = 'login' meth0d = 'post' action = 'Coutput.html' >            
        <input id ="name" type = "text"  value="">           
        <input id="btnSet" type="button" value="Go"/>
        <input id="btndelete" type="button" value="delete cookie"/>
 </form>

On my Coutput.html i have

<script src="jquery.js"></script>
<script src="jquery.cookie.js"></script>
<script>
    alert($.cookie("cookie_name") );
</script>

If you want to delete the cookie on window close, then use window.unload event and on jquery perhap this. And you can delete cookie by resetting it to null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download