2011-10-03 42 views
1

我想根據多選框選擇來填充內容。 我可以得到選擇框的所有選定值。 使用在多選框中獲取最近的選擇

$('select').change(function(){ 
    console.info($(this).val()) // it gives me array 
}); 

但我想只有最近選擇/取消用戶進行。

回答

0

試試這個

// this will set the last selected or deselected option element's value to the select element as a custom attribute "recent" 
$("#selectEl option").click(function(event) { 
    $(this).parent().attr("recent", $(this).val()); 
}); 


$("#selectEl").attr("recent"); // returns the last selected/deselected option value or undefined if attribute recent is not present 
1

你可以這樣做:

function arr_diff(a1, a2) { 
    var a = [], 
     diff = []; 
    for (var i = 0; i < a1.length; i++) 
    a[a1[i]] = true; 
    for (var i = 0; i < a2.length; i++) 
    if (a[a2[i]]) delete a[a2[i]]; 
    else a[a2[i]] = true; 
    for (var k in a) 
    diff.push(k); 
    return diff; 
} 
var oldSelect = []; 
$('select').change(function() { 
    var changes = arr_diff(oldSelect, $(this).val()); 
    console.info(changes); // it gives me array 
    oldSelect = $(this).val(); 
}); 

變化只包含selcted /取消元素

小提琴這裏http://jsfiddle.net/j5rBS/

附:你應該接受一些答案,因爲你的接受率很低

+0

感謝尼古拉,它爲我工作。 – vinay

0

或,只需剛剛獲得數組的第一個索引,而選擇。

$(function(){ 
$('select').change(function(){ 
    var opt=$(this).val(); 
    $("span").text(opt[0]); 
}); 
}) 

http://jsfiddle.net/jMw92/10/

+1

這不會給我最近的選擇,我給選擇的第一個值。 – vinay