lovo2
lovo2

Reputation: 37

jquery validation

I have a poll with a couple a questions. Here is html code

<form id="pool">
 <div class="questions>
  <input type="radio" name="sex">Male
  <input type="radio" name="sex">Female
 </div>

 <div class="questions>
  <input type="radio" name="hair">Brown
  <input type="radio" name="hair">Blonde
 </div>

 .... a lot of qestions div's
</form>

What to do so after the form is submitted to be sure that there is a checked radio button in all div`s ?

Upvotes: 0

Views: 77

Answers (4)

banners
banners

Reputation: 454

You can use the jquery validate plugin

from my experience this plugin is very efficient

Upvotes: 0

Paul
Paul

Reputation: 141927

If you know how many groups you have you can just do:

if($('#pool input:radio:checked').length < numGroups){
    // At least one group isn't checked
}

Otherwise you need to count the number of groups first. I can't think of any way to do this better then:

var rgroups = [];
$('#pool input:radio').each(function(index, el){
        var i;
        for(i = 0; i < rgroups.length; i++)
            if(rgroups[i] == $(el).attr('name'))
                return true;
        rgroups.push($(el).attr('name'));
    }
);
rgroups = rgroups.length;

if($('#pool input:radio:checked').length < rgroups)
    alert('You must fill in all the fields.');
else
    alert('Thanks!');

Upvotes: 1

Semyazas
Semyazas

Reputation: 2101

Untested code, but this is the idea:

 if($('#pool').children().length == $('pool
 div').find('#pool input:radio:selected').length) { 
 //do stuff 
 }

Upvotes: 0

hadvig
hadvig

Reputation: 1106

set default values or create handler for submit button and check if some values was checked. If no radio button is checked, show error message and do not submit form ( return false)

Upvotes: 0

Related Questions