Reputation: 3664
I have five drop down lists with the same options in my form and there should be validation that a drop down cannot have the value which already selected from previous drop down...
<select id ="selected" name="expenseType" class="dynamic_select" >
<option value="0">-select-</option>
<option value="1">Van</option>
<option value="2">SUV</option>
<option value="3">Hatcback</option>
<option value="4">Jeep</option>
</select>
On submitting, how can I validate this? I am using the jQuery validation plugin to validate the form.
Upvotes: 0
Views: 6984
Reputation: 3944
Here is some script that uses the jQuery validator framework to do what I think you're after.
<script type="text/javascript">
$(function () {
$.validator.addMethod('uniqueselection', function (v, e, d) {
if (v == '-select-') {
return true;
}
if ($(".dynamic_select option[value='" + v + "']:selected").size() > 1) {
return false;
}
return true;
});
$('select').each(function () {
$(this).rules('add', { uniqueselection: 'This can be selected once' });
});
});
</script>
Upvotes: 1
Reputation: 1127
Here you are this will alert if two select are same value, just use five instead of two acording to your needs.
<script type="text/javascript">
$(document).ready(function(){
$('#target').bind('submit', function(){
if($('#selected1').val() == $('#selected2').val()){
alert($('#selected1').val()+" "+ $('#selected2').val());
}
});
});
</script>
<form method="post" id="target">
<select id ="selected1" name="expenseType" class="dynamic_select" >
<option value="0">-select-</option>
<option value="1">Van</option>
<option value="2">SUV</option>
<option value="3">Hatcback</option>
<option value="4">Jeep</option>
</select>
<select id ="selected2" name="expenseType" class="dynamic_select" >
<option value="0">-select-</option>
<option value="1">Van</option>
<option value="2">SUV</option>
<option value="3">Hatcback</option>
<option value="4">Jeep</option>
</select>
<input type="submit" value="submit"/>
</form>
Upvotes: 0
Reputation: 69905
Try something like this
var isValid = true;
var $dynamicSelect = $("select.dynamic_select");
$dynamicSelect.each(function(){
if($dynamicSelect.find("option[value="+this.value+"]:selected").length > 1){
isValid = false;
return false;
}
});
Now use isValid
variable to show the appropriate error message or go ahead and submit the form.
Upvotes: 2