Validating a radio button is checked with jQuery

前端 未结 7 1570
你的背包
你的背包 2021-01-13 07:17

On my form I havea set of radio buttons. Here\'s the mark up:

Format

相关标签:
7条回答
  • 2021-01-13 07:25

    You could check to see if the checked radio button name returns a value in jQuery:

    if($("input[@name='fileType']:checked").val() != null){
        // button checked
    }
    
    0 讨论(0)
  • 2021-01-13 07:27

    Really old, I know. If a radio selection is not selected it returns as 'undefined', not '0'. In my example I declare a variable with the value of the radio buttons. If said value is undefined, the javascript returns false.

    gender = $('input[name=gender]:checked').val();
    
    if(typeof gender === 'undefined'){
        alert('Do not move on');
        $('input[name=gender]').css('box-shadow', '0 0 2px 0 red');
        return false;
    }    
    
    0 讨论(0)
  • 2021-01-13 07:37

    demo

    http://jsfiddle.net/Vq2jB/2/

    var isChecked = jQuery("input[name=fileType]:checked").val();
    
    0 讨论(0)
  • 2021-01-13 07:41

    You can use the length and equal attribute selector with :checked filter selector like this:

    if ($("input[name='fileType']:checked").length > 0){
      // one ore more checkboxes are checked
    }
    else{
     // no checkboxes are checked
    }
    
    0 讨论(0)
  • 2021-01-13 07:44

    Try the jQuery Validation plugin. It can do a lot for you and be really useful for lots of different forms. If you want to do it very simply:

    if($("input[name=fileType]:checked").length > 0) {
       //Is Valid
    }
    
    0 讨论(0)
  • 2021-01-13 07:44

    I think $('input[name=fileType]:checked').length will do the trick.

    0 讨论(0)
提交回复
热议问题