开发者

How to validate the radio button and checkbox?

开发者 https://www.devze.com 2023-01-31 10:17 出处:网络
For radio button: $(document).ready(function() { $(\'#select-number\').click(function() { if ($(\'input:radio\', this).is(\':checked\')) {

For radio button:

$(document).ready(function() {
        $('#select-number').click(function() {
                if ($('input:radio', this).is(':checked')) {
                    return true;
                } else {
                    alert('Please select something!');
                    return false;
            }
        });

    });

It is working fine when no radio button is selected. But When I select the radio button and submit the form Then also it is giving me 开发者_运维问答the alert message 'Please select something!' Is there any good tutorials available for validation using Jquery for newbie.


It looks like you're attaching to the click event of the submit button (there are no inputs inside that element). Instead, attach to the submit event of the form:

$(document).ready(function() {
    $('#formID').submit(function() {
        if ($('input:radio', this).is(':checked')) {
            return true;
        } else {
            alert('Please select something!');
            return false;
        }
    });
});

This has the advantages of catching all the way the <form> may be submitted, as well as looks for input:radio buttons in the correct spot. You can also shorten/simplify it down further:

$(function() {
  $('#formID').submit(function() {
    if ($(this).find('input:radio:checked').length == 0) {
      alert('Please select something!');
      return false;
    }
  });
});


I think it's because you're not seeing if a single radio is checked, rather checking if all are checked

if ($(this).find("input:radio:checked").length > 0) {
    return true;
} 
else {
    alert('Please select something!');
    return false;
}


The jQuery validation plugin is quite good and easy to get started with. If you're new to jQuery, you're probably better off trying out the plugin and focusing on other basics. You'll figure out some validation as you go, but this can get you validating (client-side) like a pro very quickly.


I think it is because of passing 'this' as second parameter to the $('input:radio') function, because passing this to the call makes jQuery to search within the context of this (which I assume is the Submit button). Try this...

$(document).ready
 (
  function() 
  {         
   $('#select-number').click
   (
    function() 
    {                 
     if ($('input:radio').is(':checked')) 
     {                     
      return true;                 
     } 
     else 
     {                     
      alert('Please select something!');                     
      return false;             
     }         
    }
   );      
  }
 ); 


This may be of help Validation of radio button group using jQuery validation plugin

0

精彩评论

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