DIV CSS 佈局教程網

jQuery 操作 Select 的進階技巧:遍歷 option、表單取值全攻略
編輯:JQuery特效代碼     

下拉選單的操作看似簡單,實則眉角不少。本文除了示範如何遍歷、新增與移除 option,還整理了一份涵蓋 select、radio、checkbox、text 各類表單元素取值與設值的實用清單,值得收藏。

遍歷 option 並動態增刪

以下函式示範了如何依條件遍歷並移除 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",'');
  • checkbox 打勾 / 取消:$("#chk2").attr("checked",true); / $("#chk1").attr("checked",'');
  • radio 選中 value=2:$("input[@type=radio]").attr("checked",'2');
  • 清空下拉框:$("#sel").empty();
  • 新增 option:$("<option value='1'>1111</option>").appendTo("#sel")

小提醒

上述帶有 @ 的屬性選擇器寫法(如 option[@selected])是早期 jQuery 的語法,在新版 jQuery 中已改為直接寫 option:selected 或 [selected]。遷移舊專案時可留意這個差異。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved