2012-04-03 73 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/希望這幫助你:]

相關問題