2012-04-03 78 views
1

考虑简单的多选框有了多个选择,我们如何才能知道用户选择了或未选择某个值?

<select name="waste" id="waste" multiple> 
<option value="5">garbage</option> 
<option value="6">food</option> 
<option value="8">Tin</option> 
<option value="9">Can</option> 
</select> 

它所做的就是火更改事件

$('#waste').change(function(){ 
//Inside here how will I know that this event was fired when user removed some values from selection 
// or did he added more values in selection 
}); 
+0

http://stackoverflow.com/questions/1159046/jquery-change-event-on-an-input-element-any-way-to-retain-previous-value;这可能有帮助。干杯! – 2012-04-03 07:36:03

回答

1

尝试这个例子:http://jsfiddle.net/7rf9J/

(function() { 
    var s = $('#waste'), 
     var i = s.val().length; 

    s.change(function(){ 
     var l = $(this).val().length; 
     if (l === i) { 
      console.log('you\'ve not changed selected value/s'); 
     } 
     else { 
      if (l > i) { 
       console.log('you inserted value/s'); 
      } 
      else { 
       console.log('you removed value/s');    
      } 
     } 
     i = l; 
    }); 
}());  

我已经将函数包含在一个即时自我执行函数中,其中我声明了一个包含所选项目数的变量。每次添加o删除项目时,我都会保存当前值的长度(最初设置为0),因此您知道是否添加,删除或更改了选择。

+0

我明白了,谢谢 – 2012-04-03 08:51:47

0

试试这个:

$('#waste').change(function(){ 
    var selected=$(this).val(); 
    // selected now contains an array of the selected values 
}); 

演示:http://jsfiddle.net/pUcRe/

0

我写的,会做正是你所需要的例子。 的例子是在这里:http://jsfiddle.net/hesher/3M36e/5/

代码:

var prevarray = []; 

$("select").change(function(event) { 
    var 
    thisarray = $(event.currentTarget).children(":selected").map(function(index, item) { 
     return $(item).text() 
    }); 



    for (i = 0; i < thisarray.length; i++) { 
     var anoption = thisarray[i]; 
     if ($.inArray(anoption, prevarray) === -1) { 

      console.log("added " + anoption); 
     } 
    } 

    for (i = 0; i < prevarray.length; i++) { 
     var anoption = prevarray[i];; 
     if ($.inArray(anoption, thisarray) === -1) { 
      console.log("removed " + anoption); 
     } 
    } 

    prevarray = thisarray; 

});​ 
0

试试这个:

<select name="waste" id="waste" multiple> 
    <option value="5">garbage</option> 
    <option value="6">food</option> 
    <option value="8">Tin</option> 
    <option value="9">Can</option> 
</select> 
<p></p> 

和JS是:

function displayVals() { 
    var wasteValues = $("#waste").val() || []; 
    $("p").html("<b>Values:</b> " + multipleValues.join(", ")); 
    } 
    $("#waste").change(displayVals); 
    displayVals(); 

或检查了这一点:http://api.jquery.com/val/希望这帮助你:]

相关问题