javascript - Avoid same option selected multiple times using jquery -


i have 2 tables table1 , table2. each table contains <select> tag , options , values same.

now want check each table, there option exists more 1 times. if yes alert option selected.

my code is:

$('#table1 tr').each(function() {     $(this).find('select').change(function() { //alert($(this).val())         if ($('option[value=' + $(this).val() + ']:selected').length > 1) {             alert('option selected');             $(this).val($(this).find("option:first").val());         }     }); });  $('#table2 tr').each(function() {     $(this).find('select').change(function() { //alert($(this).val())         if ($('option[value=' + $(this).val() + ']:selected').length > 1) {             alert('option selected');             $(this).val($(this).find("option:first").val());         }     }); }); 

when select same in first table , second table alert option selected. what's wrong code?

you can test code here.

the problem selecting options (table1 + 2) whereas should have selected options belonging current table, such 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 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 selected');             $(this).val($(this).find("option:first").val());            }     }); }); 

demo@fiddle

edit:

a better version:

// have class if will, 2 tables (or more) avoid use of id's may not need them // <table class="grouped-select" ... > // , do: // $('.grouped-select').find('select').on('change', function() { // or use tag selector $('table').find('select').on('change', function() {     //cache jquery references you'd reuse on , on     var $this = $(this);     if( $this.closest('table').find('select option[value=' + $this.val() + ']:selected').length > 1) {         alert('option selected');         $this.val($this.find("option:first").val());     } }); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -