首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

jQuery 表單元素值獲取與賦值完全指南:Radio、Checkbox、Input、Select

     編輯:PHP 相關知識

jQuery 操作表單元素是前端開發高頻需求。本文系統整理了 Radio(單選)、Checkbox(多選)、Input(文本/隱藏域)、Select(下拉框)、Textarea(文本域) 的值獲取、賦值、狀態判斷及動態控制方法,並修正了常見錯誤寫法。

Radio 單選組

獲取選中值

// ✅ 標準寫法
$("input[name='gender']:checked").val();

// 獲取選中項的下一個元素文本(如標籤文本)
$("input[name='gender']:checked").next().text();

設置選中項

// 按 value 設置
$("input[name='gender'][value='male']").prop('checked', true);
// 或
$("input[name='gender']").val(['male']); // jQuery 1.6+ 推薦

Checkbox 多選框

判斷是否勾選

// ✅ 推薦:prop() (jQuery 1.6+)
$("#agree").prop("checked"); // true/false

// ⚠️ 不推薦:attr() 返回屬性初始值,不反映當前狀態
$("#agree").attr("checked"); // "checked" 或 undefined

獲取值

$("#agree").val(); // 返回 value 屬性值

賦值/設置勾選狀態

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

// 批量設置:按 value 陣列
$("input[name='hobby']").val(['reading', 'coding']);

獲取所有勾選值(陣列)

var checkedVals = $("input[name='hobby']:checked").map(function(){
    return $(this).val();
}).get(); // ['reading', 'coding']

Input 文本框 / 隱藏域 / Textarea

獲取/設置值

$("#username").val();        // 獲取
$("#username").val("新值");    // 設置
$("#username").val("");        // 清空

屬性操作

$("#username").attr("readonly", true);   // 只讀
$("#username").removeAttr("readonly");   // 移除只讀
$("#username").prop("disabled", true);   // 禁用

Select 下拉框

獲取值與文本

$("#city").val();                              // 獲取 value
$("#city").find("option:selected").text();     // 獲取顯示文本
$("#city").get(0).selectedIndex;               // 獲取索引

設置選中項

$("#city").val("beijing");                     // 按 value 設置(推薦)
$("#city").get(0).selectedIndex = 2;           // 按索引設置
$("#city option[text='北京']").prop("selected", true); // 按文本設置

動態操作 Option

// 添加
$("#city").append("");
$("#city").prepend("");

// 刪除
$("#city option:last").remove();               // 刪除最後
$("#city option[value='3']").remove();         // 刪除指定 value
$("#city option[index='0']").remove();         // 刪除指定索引

// 清空
$("#city").empty();

通用獲取方法(表單序列化)

// 獲取整個表單數據(對象/字符串)
var formData = $("#myForm").serializeArray(); // [{name, value}, ...]
var formStr  = $("#myForm").serialize();      // "name=value&..."

// 設置表單數據(需插件或手動循環)
$.each(formData, function(i, field){
    $("[name='"+field.name+"']").val(field.value);
});

核心原則總結

  • 值操作用 .val():Input、Select、Textarea、Checkbox/Radio(陣列賦值)統一用 .val()。
  • 狀態/屬性用 .prop():checked、disabled、selected、readonly 必須用 .prop(),禁用 .attr()。
  • 文本內容用 .text() / .html():獲取選項顯示文本、設置標籤內容。
  • 選擇器精準::checked、:selected、[name='x'] 組合使用。

遵循以上原則,能避開 90% 的 jQuery 表單操作坑,編寫健壯、可維護的交互代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved