jQuery 版本不同寫法略有差異,本文基於 jQuery 1.3.2 整理最常用的表單取值/設值/事件綁定代碼,適合快速查閱。
| 元素類型 | 取值代碼 | 備註 |
|---|---|---|
| 文字框/域 | $("#txt").val() / $("#txt").attr("value") | 推薦 .val() |
| Radio 單選組 | $("input[name='radio_name']:checked").val() | 直接取被選項 value |
| Checkbox 多選 | $("input[name='chk']:checked").map(function(){return this.value;}).get() | 回傳陣列 |
| Select 下拉單選 | $("select").val() | 取 value |
| Select 取顯示文字 | $("select option:selected").text() 或 $("select").find("option:selected").text() |
$("input[name='r'][value='2']").prop("checked", true);$("#chk_id").prop("checked", true/false);$("#sel").val("targetValue");$("<option value='1'>文字</option>").appendTo("#sel");$("#sel").empty();$("#txt").focus(fn); // 取得焦點
$("#txt").blur(fn); // 失去焦點
$("#txt").select(); // 選取文字內容
.prop() 處理 checked、selected、disabled 等布林屬性;.attr() 僅處理 HTML 屬性。[@attr] 語法在 1.3 後已移除,改用 [attr]。