表單元素值的獲取與設置是前端高頻操作,本文彙總 jQuery 對 select、radio、checkbox 的標準 API 與常見坑點。
// 獲取
var val = $('#sel').val(); // value
var txt = $('#sel').find('option:selected').text(); // text
var idx = $('#sel').prop('selectedIndex'); // 索引
// 設置
$('#sel').val('2'); // 通過 value
$('#sel').prop('selectedIndex', 1); // 通過索引
$('#sel option[value="2"]').prop('selected', true); // 通過屬性
// 添加/刪除選項
$('#sel').append('<option value="3">三</option>');
$('#sel option:last').remove();
$('#sel option[value="2"]').remove();
// 獲取選中值
var val = $('input[name="sex"]:checked').val();
// 設置選中(通過 value)
$('input[name="sex"][value="1"]').prop('checked', true);
// 遍歷
$('input[name="sex"]').each(function() {
console.log(this.value, this.checked);
});
// 獲取所有勾選值(陣列)
var vals = $('input[name="hobby"]:checked').map(function() { return this.value; }).get();
// 判斷單個是否勾選
var checked = $('#chk1').prop('checked'); // true/false
// 設置勾選狀態
$('#chk1').prop('checked', true); // 勾選
$('#chk1').prop('checked', false); // 取消
// 全選/反選
$('#checkAll').on('change', function() {
$('input[name="hobby"]').prop('checked', this.checked);
});
var data = $('#myForm').serializeArray(); // [{name:'sex',value:'1'}, ...]
var str = $('#myForm').serialize(); // "sex=1&hobby=reading&hobby=coding"
var obj = $('#myForm').serializeJSON(); // 需插件,或自行 reduce
.prop() 操作 checked/selected/disabled 等布爾屬性**,.attr() 僅用於 HTML 屬性(如 id、class)。:checked 偽類僅匹配當前勾選項,配合 name 選擇器精確定位單選組。