萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 獲取單選框、復選框、下拉框選中值的標準方法

HTML 表單示例

<form id="demoForm">
  <!-- 單選框 -->
  <input type="radio" name="sex" value="男" id="r1"><label for="r1">男</label>
  <input type="radio" name="sex" value="女" id="r2"><label for="r2">女</label>

  <!-- 復選框 -->
  <input type="checkbox" name="hobby" value="読書" id="c1"><label for="c1">読書</label>
  <input type="checkbox" name="hobby" value="旅行" id="c2"><label for="c2">旅行</label>
  <input type="checkbox" name="hobby" value="運動" id="c3"><label for="c3">運動</label>

  <!-- 下拉框 -->
  <select name="city" id="city">
    <option value="">請選擇</option>
    <option value="bj">北京</option>
    <option value="sh">上海</option>
    <option value="gz">廣州</option>
  </select>
</form>

jQuery 獲取值的標準 API

控件類型獲取值獲取文本設置值
單選框$('input[name="sex"]:checked').val()$('input[name="sex"]:checked + label').text()$('input[name="sex"][value="男"]').prop('checked', true)
復選框(多選)$('input[name="hobby"]:checked').map(function(){return this.value;}).get() → 數組.map(function(){return $(this).next('label').text();}).get().prop('checked', true/false)
下拉框$('#city').val()$('#city option:selected').text()$('#city').val('sh')

完整交互示例

<script>
$(function() {
  // 1. 單選框點擊即時獲取
  $('input[name="sex"]').on('change', function() {
    console.log('性別:', $(this).val());
  });

  // 2. 復選框獲取所有選中值
  $('#getHobby').click(function() {
    var hobbies = $('input[name="hobby"]:checked').map(function() {
      return {value: this.value, text: $(this).next('label').text()};
    }).get();
    console.log('愛好:', hobbies);
  });

  // 3. 下拉框 change 事件
  $('#city').on('change', function() {
    var val = $(this).val();
    var txt = $(this).find('option:selected').text();
    console.log('城市 value:', val, 'text:', txt);
  });

  // 4. 表單序列化(一鍵獲取所有)
  $('#submit').click(function(e) {
    e.preventDefault();
    var data = $('#demoForm').serializeArray(); // [{name, value}, ...]
    console.log('表單數據:', data);
    // 或 serialize() 得到查詢字符串
    console.log('查詢串:', $('#demoForm').serialize());
  });
});
</script>

進階技巧

  • 判斷單選框是否選中:if ($('input[name="sex"]:checked').length) { ... }
  • 反選復選框:$('input[name="hobby"]').each(function(){ this.checked = !this.checked; });
  • 禁用/啟用:.prop('disabled', true/false)。
  • 動態添加選項:$('#city').append('');

原生 JS 對照(無依賴)

// 單選
document.querySelector('input[name="sex"]:checked')?.value;

// 復選框多值
[...document.querySelectorAll('input[name="hobby"]:checked')].map(e => e.value);

// 下拉框
document.getElementById('city').value;
document.getElementById('city').selectedOptions[0].text;
copyright © 萬盛學電腦網 all rights reserved