开发者

jquery submit form problem

开发者 https://www.devze.com 2023-01-26 07:10 出处:网络
I have a form with radio buttons in it. Before the form submits I need to check that 10 radio buttons are checked. This code does the trick (i.e. I get the alert back when 10 have been checked) but I

I have a form with radio buttons in it. Before the form submits I need to check that 10 radio buttons are checked. This code does the trick (i.e. I get the alert back when 10 have been checked) but I can't work out where to put my return true and return false statements to stop it or let it submit if my count has reached 10.

  $('.submit').click(function () {
      var radios = $(':radio');
      var count = 0;
      $.each(radios, function () {
          if ($(this).is(':checked')) {
              count++;
              alert(count);
          }

          if (count === 10) {
              alert('hi')
              return true;
          }
      })
      return false;
})

At the moment the return false at the b开发者_JAVA百科ottom stops the form submitting even when the count is 10 but I need to return false in there to stop the form submitting right away.

Hope this makes sense.


Use event.preventDefault() instead of return false;. Also, use the submit event instead of the click event:

var the_form = $('#theformid');
the_form.submit(function (event) {
    var radios = the_form.find(':radio:checked');
    if (radios.length !== 10) {
        event.preventDefault();
        // provide feedback here.
    }
});

If you attach to the click event, your form can still be submitted using the keyboard.


Try something like this:

$('.submit').click( function(){
  return $('#yourform :radio:checked').length == 10;
});

Hopefully there's a container id like #yourform you can use to make the selector more specific, as above.


Edit: As per your comment, if you want to intercept the form submission reliably (e.g., even when submitted without the button being clicked), as others have suggested you should attach behavior to the form's submit event.

$('#yourform').submit( function(e){
  var hasTen = $(this).find(':radio:checked').length == 10;
  if( !hasTen ){
    e.preventDefault();
    alert('Please check ten boxes.');
  }
});


Why do you check the count inside the iteration ? You should solve it by putting the check outside the each func.

$('.submit').click(function () {
  var radios = $(':radio');
  var count = 0;
  $.each(radios, function () {
      if ($(this).is(':checked')) {
          count++;
      }          
  });

  if (count == 10) {
          return true;
          alert("great!");
  }
  return false;
})

I also suggest you to use console.log(msg) instead of alert(msg), way much better to debug ;)

EDIT: I see now your comment about the alert, I thought it was there for debug purposes that's why a told you about the console.log ;)

0

精彩评论

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

关注公众号