简体   繁体   中英

Jquery validate and a list of select box

How Can i specific require and unique condition for a list of select box like below?

<form name="signupForm" class="cmxform" id="signupForm" method="get" action="">
<select name="category[]" id="cat_1">
<option value="">Select One</option>
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
<option value="4">dd</option>
</select>
<select name="category[]" id="cat_2">
<option value="">Select One</option>
<option value="5">ee</option>
<option value="6">ff</option>
<option value="7">gg</option>
<option value="8">hh</option>
</select>
<select name="category[]" id="cat_3">
<option value="">Select One</option>
<option value="9">ii</option>
<option value="10">jj</option>
<option value="11">kk</option>
<option value="12">ll</option>
</select>
<input class="submit" type="submit" value="Submit">
</form>

Notice that there are the number of cat is not fixed, it can be more than 3,

so how to make it required for each selectbox,

and each selectbox chosen value must be unique using jquery validate plugin? Thank you

var $selects = $('form select[name^=category]'),
    values = [];

$(':submit').click(function(e) {
  e.preventDefault();
  values = [];
  $($selects).each(function() {
      if($(this).val()) {
          values.push($(this).val());        
      }
  });
    if(!values.length) {
        alert('Please select all categories');
        return false;
    }
  if(values.length < $selects.length || $.unique(values).length < $selects.length) {
    alert('Please select all categories and be unique');
    return false;
  }
});

DEMO

Here is a great jQuery validation plugin that will make your life easier: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

This is all you need to do: (the plugin does the rest)

<select id="sport" class="validate[required]" name="sport">
<option value="">--Select--</option>
<option value="option1">Tennis</option>
<option value="option2">Football</option>
<option value="option3">Golf</option>
</select>

Hope that helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM