DIV CSS 佈局教程網

jQuery 操作單選框、多選框、下拉選單的常用語法彙整
編輯:JavaScript綜合知識     

表單操作是 jQuery 最常被使用的場景之一,但取值、設值、增刪選項的寫法繁雜,很容易忘記。這篇把單選鈕、複選框、下拉選單與文字框的常見操作整理成可查閱的清單。

一、取值:單選、下拉與索引

var sex = $("input[name='sex']:checked").val();  // 取得一組 radio 中被選中項的值
var item = $("#sel option:selected").text();     // 取得 select 被選中項的文字
var option_num = $('#sel').val();                // 取得 select 被選中項的值

$("#sel")[0].selectedIndex = 1;                  // 讓 select 第二個項目成為選中值
$("input[name='sex']").get(1).checked = true;    // 讓 radio 組第二個項目成為選中值

依 value 設定 radio 的預設選取

$("input[name='sex']").each(function () {
  if ($(this).val() == s) {
    $(this).attr("checked", true);
  }
});

二、依 value 設定下拉列表的預設選中項

<select name="sel" onchange="bao(this.options[this.options.selectedIndex].value)">
  <option value="">請選擇</option>
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
  <option value="3">Item 3</option>
</select>

<script>
function bao(s) {
  txt.value = s;
  // 讓第一項被選中,這樣就能再次觸發 change
  document.all.sel.options[0].selected = true;
}
</script>

<textarea id="txt"></textarea>

三、jQuery 取得 Select 的 Text 與 Value

$("#select_id").change(function () { /* 選擇其中一項時觸發 */ });

var checkText  = $("#select_id").find("option:selected").text(); // 文字
var checkValue = $("#select_id").val();                          // 值
var checkIndex = $("#select_id").get(0).selectedIndex;           // 索引
var maxIndex   = $("#select_id option:last").attr("index");      // 最大索引

四、jQuery 設定 Select 的選中項

$("#select_id").get(0).selectedIndex = 1;                       // 以索引指定
$("#select_id").val(4);                                         // 以 value 指定
$("#select_id option[text='jQuery']").attr("selected", true);    // 以文字指定

五、新增與刪除 Option

$("#select_id").append("<option value='Value'>Text</option>");   // 附加到尾端
$("#select_id").prepend("<option value='0'>請選擇</option>");    // 插入到最前面
$("#select_id option:last").remove();                            // 刪除最後一項
$("#select_id option[index='0']").remove();                      // 刪除索引 0
$("#select_id option[value='3']").remove();                      // 刪除 value 為 3
$("#select_id option[text='4']").remove();                       // 刪除 text 為 4

六、完整應用:動態建立下拉選單並回顯選擇

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 表單操作範例</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
    // 初始化下拉列表:動態加入選項
    var item = ['幼兒園', '小學', '初中', '高中', '大學', '研究生', '博士', '碩士'];
    var html = "<option value='0'>請選擇</option>";
    for (var i = 0; i < item.length; i++) {
      html += "<option value='" + (i + 1) + "'>" + item[i] + "</option>";
    }
    $("#grade").empty().append(html);
    $("#grade option[value='0']").attr("selected", "selected"); // 預設第一項
  });

  // 選擇其中一項時觸發
  function showIt() {
    var selectText  = $("#grade option:selected").text();  // 文字
    var selectValue = $("#grade").val();                   // 值
    var selectIndex = $("#grade").get(0).selectedIndex;    // 索引

    var text = '選擇:' + selectText + "\n";
    text += 'value 值:' + selectValue + "\n";
    text += '索引值:' + selectIndex;
    $("#text").text(text);
  }
</script>
</head>
<body>
  <div>
    <select name="grade" id="grade" onchange="showIt()"></select>
    <p><textarea name="text" id="text" rows="30" cols="100"></textarea></p>
  </div>
</body>
</html>

版本差異提醒

上述寫法在 jQuery 1.x 時代很常見,但 .attr("checked", true) 這類用法在新版中已不建議。從 jQuery 1.6 起,表單元素的目前狀態應改用 .prop():

$("#chk").prop("checked", true);    // 勾選
$("#chk").prop("checked", false);   // 取消勾選

attr 讀的是 HTML 上的初始屬性,prop 讀的是元素當下的實際狀態,兩者在動態操作時會給出不同結果。另外 text='4' 這種以文字挑選 option 的选择器在 jQuery 3.x 已被移除,需改用 filter() 自行比對。

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