开发者

jquery submit form with checkbox

So I want to submit only when a checkbox is checked (I want to do something else when a checkbox is unchecked). I've been trying to get this checkbox submit to work but not no avail. Here's what I have:

$('#checkbox').click(function() { 
    if ($(this).attr('checked')) {
        $("#form").submit(function () {
            var newvals = $("#form").serialize();   // serialize data

            $.post('save.php', newvals, function(data) { 
                $("#content").html(data);
            }); // posting data and dumping response onto page      

            return false;
        }); 

    开发者_StackOverflow社区} else {

        alert(2); // placeholder for what i want to do otherwise
    }

});

I looked around and was poking around with .trigger and .live, but I'm having problems even thinking about how the logic would even work with those functions. I'm not opposed to using them as long as I can distinguish between a 'checked' box and an 'unchecked' box.

Any ideas?


In your code you are attaching the form submit event handler everytime you check the checkbox. It is not going to trigger the submit event and do what you are expecting.

You should attached the submit event handler outside the click event handler of checkbox and trigger the submit event of form when checkbox is checked. Try this

$function(){

    $("#form").submit(function () {

      var newvals = $("#form").serialize(); // serialize data
      $.post('save.php',newvals,function(data) { 
        $("#content").html(data);
      });   // posting data and dumping response onto page      

      return false;
    });   

   $('#checkbox').click(function() { 
    if(this.checked) {//Just this.checked will say whether its checked or not
        //Now trigger the form submit event
        $("#form").trigger('submit');
    } 
    else{
       alert(2); // placeholder for what i want to do otherwise

       //I think you want to erase the textboxes. 
       //You can find all the input elements and set there value to empty
       $("#form input").val('');
    }
   });

});


Turn the logic inside-out - attach a handler to the form submission and, in there, check to see if your input is checked. I might do something like this:

$(function(){
    $('form').submit(function(e){
        e.preventDefault();

        if ($('#checkbox').is(':checked')) {
            alert('submit');
        } else {
            alert('do not submit');
        }

    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜