2013-04-29 55 views
1

什么是检查以下使用jQuery的最佳方法添加到页面:如果选择了相同的值检查是否选择了相同的值,如果超过一个下拉菜单中使用jQuery

检查看看如果不止一个下拉菜单中使用jQuery

添加到页面中我有一个页面上的一个下拉菜单:

<select name="brand" class="brands" onchange="some function to check for the same value> 
<option>Brand 1</option> 
<option>Brand 2</option> 
<option>Brand 3</option> 
</select> 

我也必须动态地添加更多的下拉列表的能力。每个动态下拉菜单都使用相同的数据作为选项。所以我可以有这个当我点击添加按钮,显示一个新的下拉菜单:

<select name="brand_1" class="brands" onchange="some function to check for the same value"> 
<option>Brand 1</option> 
<option>Brand 2</option> 
<option>Brand 3</option> 
</select> 

,并再次:

<select name="brand_2" class="brands" onchange="some function to check for the same value"> 
<option>Brand 1</option> 
<option>Brand 2</option> 
<option>Brand 3</option> 
</select> 

等等...

我猜我可以使用class元素,也许jQuery中的下拉列表的onchange()事件,但不知道这样做的最佳方式。 任何想法或帮助指引我在正确的方向将非常感激。

感谢

JC

回答

1

我认为这可能是一个解决方案。 FIDDLE
但它只会工作是select元素是一个接一个。

$('select').on('change', function() { 
    var val = $(this).val(); // get the value of the current changed select 
    var i = $(this).index(); // get it's index (position in the group starting from 0) 
    $('select:not(:eq('+i+'))').each(function() { // loop through each select 
     if ($(this).val() === val) { // check if the value of the next select 
            // is the same as the changed one 
      alert($(this).index()+' has the same value'); 
      // alert the ones with the same value 
     } 
    }); 
}); 
+0

非常感谢您的回答。我应该提到我们正在使用jQuery版本1.6.4。我得到以下错误,我认为是连接到我们正在使用的jQuery版本:$(“select”)。on不是函数 – jeeperscreepers 2013-04-29 09:25:36

+0

试试这个http://jsfiddle.net/Spokey/UtNJD/2/ – Spokey 2013-04-29 09:41:26

+0

好的我已经摆脱了错误,谢谢你,现在我遇到的问题是,如果我将第一个选择更改为2,第二个更改为2我得到的消息是正确的。如果我然后将第一个选择框更改回1,我仍然会得到相同的错误消息,即使它被改回,任何想法?同样的行为也发生在你的小提琴示例中。 – jeeperscreepers 2013-04-29 10:50:55

相关问题