2011-09-07 68 views
1

我還在學習我周圍的jQuery的方式,但我認爲這可能是非常簡單的:如何使用jQuery修改下拉列表

我有名字和編號2個下拉框:topnumberbottomnumber

這兩個列表都包含數字1-5。

我想要做的就是使用jQuery禁用或從bottomnumber中刪除任何數字比他們在頂部數字(相等是OK)中選擇的更大。例如,如果他們在topnumber中選擇3,則將從bottomnumber列表中刪除或禁用4和5。

任何幫助表示讚賞。謝謝! Chris

回答

2

試試這個

工作demo

$(function(){ 
    $('#topnumber').change(function() { 
    var topValue = parseInt(this.value); 

    $('#bottomnumber option').attr("disabled", false).filter(function(){ 
     //This will make sure to select only options with value > topValue 
     return (topValue < parseInt(this.value)); 
    }).attr("disabled", true); 
    }); 
}); 
0

您需要綁定到每個下拉列表的更改事件,並根據用戶輸入的內容更改另一個的值。

爲此,請使用jQuery's。例如change,例如

$("#bottomnumber").change(function() { 
$(this).val() - this will be the selected value 
$("#topnumber")...do stuff to the top number one 
}); 

反之亦然。

希望有助於......不是完整的代碼,而是應該讓你走向正確的方向。

0

Here是一個生動的例子。

$(document).ready(function(){ 
    buildBottomOptions(); 
}); 

$('#top').change(function() { 
    buildBottomOptions(); 
}); 


function buildBottomOptions() { 
    var value = $('#top').val(); 
    var options = ''; 

    for (i = 1; i <= value; i++) 
     options += '<option value="' + i + '">' + i + '</option>'; 

    $('#bottom').find('option').remove().end().append(options); 
} 
1

Working Example

$('#topNumber').change(function() { 
    var num = $(this).val(); 
    $('#bottomNumber option').removeAttr('disabled').filter(function() { 
     return Number($(this).attr('value')) >= num; 
    }).attr('disabled', 'disabled'); 
}); 

該代碼使用filter()減少匹配的選項集到比val越大的人,然後禁止在匹配集合中的所有選項。

+0

一旦禁用它不會啓用如果再上面的數字被更改的選項,看看我的答案。 – ShankarSangoli

+0

這是正確的。我可以鏈接一個'attr'調用。我會更新我的答案。 –

0

使用:gt selector可以讓你做到這一點很容易。 Working example

$("#topnumber").change(function(e) { 
    // turn the value of #topnumber in a javascript integer 
    var num = parseInt($(this).val()); 
    // :gt is zero-indexed, which means that :gt(0) will get 2,3,4,5 
    // and 1 would get 3,4,5 etc, etc.., so subtract one. 
    num = num - 1 
    // reset the list so that everything is active. 
    $("#bottomnumber option").removeAttr('disabled'); 
    // disable the ones which are higher than topnumber's value 
    $("#bottomnumber option:gt("+num+")").attr('disabled', 'disabled'); 
}); 
+0

如果這些值與[1,2,3 ....]不同,該怎麼辦? :gt(值)不起作用。 – ShankarSangoli

+0

這當然值得指出:數字必須是連續的,從1開始才能正確工作。 –

0
$(document).ready(function() { 
    $('select[id="topnumber"]').change(function() { 
     var maxValue = parseInt($('select[id="topnumber"]').attr('value')); 
     $(' select[id="bottomnumber"] option').attr('disabled', false).filter(function() { 
      return parseInt($(this).attr('value')) > maxValue ; 
     }).attr('disabled', true); 
    }); 
}); 

見這裏的例子:http://jsfiddle.net/XLUju/