2017-03-22 263 views
1

我有一个动态引导多个下拉选择器。Jquery检测引导多个选项下拉被取消选择

我想运行一些代码,当用户取消选择一个选项。

<select id="selectOptions" multiple> 
    <option>Test1</option> 
    <option>Test2</option> 
    <option>Test3</option> 
    <option>Test4</option> 
    <option>Test5</option> 
<option>Test6</option> 
</select> 

我想通过jQuery来做到这一点,但是我有哪些已经在选择一个选项运行一个选择,我会怎么做,当用户点击取消选择该选项。

感谢

回答

1

你可以做的是一个change监听器添加到select元素,并保持所有项目的数组这名听众上次被选中时被选中。通过这种方式,您可以将当前选中的项目数组与之前选定项目的数组进行比较,以确定哪些项目未被选中。

下面是一个例子:

var prevSelected = []; 
 
$("#selectOptions").change(function(){ 
 
    var selected = $(this).val() || []; 
 
    var unselected = prevSelected.filter(function(v){ 
 
    return selected.indexOf(v) === -1; 
 
    }); 
 
    if(unselected.length){ 
 
    console.log("value(s) " + unselected + " were/was unselected"); 
 
    } 
 
    prevSelected = selected; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="selectOptions" multiple> 
 
    <option>Test1</option> 
 
    <option>Test2</option> 
 
    <option>Test3</option> 
 
    <option>Test4</option> 
 
    <option>Test5</option> 
 
<option>Test6</option> 
 
</select>

+0

惊人的,我需要改变了jQuery: 的$(document)。在( '变', '#selectOption',函数(){} 然而 一切工作现在由于 –

+0

@JakeS我很高兴我!可以帮助,祝你好运。 – Titus

0

this后,你可以检查选择的值,像这样

var select = document.getElementById("selectOptions"); 
$('#selectOptions').change(function(){ 
    for (index in select){ 
     if ($("#selectOptions").val() === "") 
      { 
       //some code 
      } 
    } 
}); 
+0

我需要知道什么时候一个值已成为未被选择和哪一个。我认为这不会有帮助。 –

+0

@JakeS我做了一个编辑,可能会更接近你所要求的。 –