I have two tables Table1 and Table2.
Each table contains tag and the options and their values were same.
Now I want to check for each table,
The problem was that you were selecting all options (table1 + 2) whereas you should have selected options belonging to the current table, such as below.
$('#table1 tr').each(function() {
$(this).find('select').change(function(){//alert($(this).val())
if( $('#table1').find('select option[value='+$(this).val()+']:selected').length>1){
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}
});
});
$('#table2 tr').each(function() {
$(this).find('select').change(function(){//alert($(this).val())
if($('#table2').find('select option[value='+$(this).val()+']:selected').length>1){
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}
});
});
Demo@Fiddle
Edit:
A slightly better version:
// Have a class if you will, for your 2 tables (or more) which would avoid the use of ID's as you may not even need them
//
// and then do:
// $('.grouped-select').find('select').on('change', function() {
// or just use tag selector
$('table').find('select').on('change', function() {
//Cache jQuery references that you'd reuse over and over
var $this = $(this);
if( $this.closest('table').find('select option[value=' + $this.val() + ']:selected').length > 1) {
alert('option is already selected');
$this.val($this.find("option:first").val());
}
});
- 热议问题