下拉選單的操作看似簡單,實則眉角不少。本文除了示範如何遍歷、新增與移除 option,還整理了一份涵蓋 select、radio、checkbox、text 各類表單元素取值與設值的實用清單,值得收藏。
以下函式示範了如何依條件遍歷並移除 option,或動態追加新選項:
function changeShipMethod(shipping){
var len = $("select[@name=ISHIPTYPE] option").length;
if(shipping.value != "CA"){
$("select[@name=ISHIPTYPE] option").each(function(){
if($(this).val() == 111){
$(this).remove();
}
});
}else{
$("<option value='111'>UPS Ground</option>").appendTo($("select[@name=ISHIPTYPE]"));
}
}
$('#testSelect option:selected').text();
或 $("#testSelect").find('option:selected').text();
或直接 $("#testSelect").val();
$(".formc select[@name='country'] option[@selected]").text();$('.formc select[@name="country"]').val();$("input[@type=radio][@checked]").val();$("input[@type=checkbox][@checked]").val();$("#txt").attr("value");$("#txt").attr("value",'');$("#chk2").attr("checked",true); / $("#chk1").attr("checked",'');$("input[@type=radio]").attr("checked",'2');$("#sel").empty();$("<option value='1'>1111</option>").appendTo("#sel")上述帶有 @ 的屬性選擇器寫法(如 option[@selected])是早期 jQuery 的語法,在新版 jQuery 中已改為直接寫 option:selected 或 [selected]。遷移舊專案時可留意這個差異。