Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add jQuery Validation Rule to a Radio Button Group

I'm using jQuery Validation Plugin and I want to be able to dynamically add and remove validation from 3 radio button groups.

I am able to dynamically add and remove validation from text field input using the sample code below:

<script type="text/javascript">
    $(document).ready(function(){   

        //Add Requird Validation
        $("#inputTextField").rules("add", "required");

        //Remove Required Validation
        $("#inputTextField").rules("remove", "required");

    });
</script>

Is it possible to do the same with radio buttons?

like image 320
AlGallaf Avatar asked Oct 21 '22 17:10

AlGallaf


1 Answers

The code as you've posted it will work fine. However, rules('add') must come after .validate() and each input must contain a name attribute even if you're not targeting by name.

HTML:

<form id="myform">  
     <input type="text" name="field" id="inputTextField" /> <br/> 
</form> 

jQuery:

$(document).ready(function() {

    $('#myform').validate({
        // other options & rules
    });

    // must come afer validate()
    $("#inputTextField").rules("add", {
        required: true
    });

});

Demo: http://jsfiddle.net/fnKWD/

Is it possible to do the same with radio buttons?

Of course, just target them by name or by any other valid jQuery selector.

$('input[name="myname"]')

HTML:

<input type="radio" name="myname" value="0" />
<input type="radio" name="myname" value="2" />
<input type="radio" name="myname" value="5" />

Demo: http://jsfiddle.net/LkJZw/

like image 176
Sparky Avatar answered Oct 24 '22 09:10

Sparky