简体   繁体   中英

Perform action on check box

How can I change this function so that it performs it after a user checks a box, instead of clicking on a button? Also, if they uncheck, another function gets executed.

 $("#saveData")
     .click(function (e) {
     e.preventDefault();
     localStorage.setItem("flag", "set");
     var data = $("#form1").serializeArray();
     $.each(data, function (i, obj) {
         if (obj.name != "creditCard") {
             localStorage.setItem(obj.name, obj.value);
         }
     });
 });

Here's the input field,

<input id="saveAddress" type="checkbox" name="address">Save Address

Well, with there information I have here are some basic guidlines:

$('#checkbox_element').change(function(){
  if(this.checked){
    //checkbox checked, do your thing
  }else{
    //it has been unchecked
  }
});

JSFiddle Example: http://jsfiddle.net/uHEhh/1/

Change $("#saveData").click to $("#saveAddress").click , so you get something like:

$("#saveAddress")
     .click(function (e) {
     e.preventDefault();
     localStorage.setItem("flag", "set");
     var data = $("#form1").serializeArray();
     $.each(data, function (i, obj) {
         if (obj.name != "creditCard") {
             localStorage.setItem(obj.name, obj.value);
         }
     });
 });

(also you can use $(this).(':checked') inside the event handler to perform different actions for checking/unchecking)

You could do it like this:

 $("#saveAddress").click(function(e) {
   if($(this).prop("checked")) {
    localStorage.setItem("flag", "set");
    var data = $("#form1").serializeArray();
    $.each(data, function(i, obj) {
        if(obj.name != "creditCard") {
            localStorage.setItem(obj.name, obj.value);
        }
    });             
   } else {
       /*Other function code*/
   }
});

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