简体   繁体   中英

Comparing checkbox checked state versus page load state on form submit

I have multiple checkboxes on page and on form submission, I wish to not send all those checkboxes for processing, but only those whose state has changed from the one on page load.

For example, on page load a checkbox's original state was checked.

Then the user clicks on that same checkbox 3 times and then clicks the submit button:

  • 1st click - State changed to unchecked
  • 2nd click - State changed to checked
  • 3rd click - State changed to unchecked

So is there a way we can compare the 3rd click state with the page load state? In this case, I would want to send that checkbox data since its state has changed. On the other hand, if the user clicks two times, I do not want to send it for processing since its state has gone back to the same during page load.

When you submit a html form, all checkboxes are submitted unless they have "disabled" attribute.

One strategy may be adding an hidden field holding checkbox's value, and check these two against each other onSubmit, and disable the checkbox if they contain the same value.

In that case you can try some thing like this:

$(document).ready(function(){
   // get check box state at the time of page load
   if($('#chk1').is(':checked'))
   {
       var chkState1 = true;
   }
   else
   {
       var chkState1 = false;
   }

   $('#chk1').change(function(){
       // get new state of this check box and compare it with the old one. If its state is diff than put it in the ajax call otherwise not
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM