表單是 Web 應用最古老也最關鍵的一塊。以下依元素類型整理取值、設值與狀態控制的標準寫法。
var v = $("#text").val(); // 取值
var v = $("#text").attr('value'); // 亦可,但前提是 HTML 上有 value 屬性,否則回傳 undefined
$("#text").val('test'); // 設值
$("#text").attr('value', 'test'); // 亦可
一般、重置與提交按鈕的寫法同上。若標籤上沒有 value 屬性,attr('value') 回傳 undefined,而 val() 回傳空字串。
$("#check").val(); // 取值
$("#check").attr('value'); // 亦可
// 取得所有被勾選的值
$("input[type=checkbox][checked]").each(function(){
alert($(this).val());
});
// 全選 / 取消全選
$("[name='test1']").attr("checked", 'checked');
$("[name='test1']").removeAttr("checked");
// 反選
$("[name='test1']").each(function(){
if($(this).attr("checked")) { $(this).removeAttr("checked"); }
else { $(this).attr("checked", 'true'); }
});
若要一次取出多個勾選值並送到後端,建議把 name 設成 name="xxx[]" 形式,伺服器端會自動收為陣列。
$("#slt").val(); // 取得選中項的值
$("#slt").val('audi'); // 設值,無對應選項則不變動
$("#slt option:selected").text(); // 取得選中項的文字
$("#slt").get(0).selectedIndex; // 取得索引
$("#slt").get(0).selectedIndex = index; // 設定索引,超過上限會變 -1
$("#slt").empty(); // 清空
$('#<option value="1">1</option>').appendTo($("#slt")); // 新增選項
$("#slt option[value='opel']").remove(); // 刪除指定選項
$("#text").attr("disabled", true); // 停用
$("#text").removeAttr("disabled"); // 啟用
上面不少寫法取自 jQuery 1.6 之前的習慣。1.6 之後,checked、selected、disabled 這類布林狀態請改用 prop():
$("#check").prop("checked", true); // 勾選
$("#check").prop("checked", false); // 取消勾選
$("#text").prop("disabled", true); // 停用
原因很單純:attribute 記錄的是 HTML 上寫死的初始值,property 才是元素的即時狀態。用 attr() 改布林屬性,在部分瀏覽器上會出現「設了卻沒生效」的怪象,這正是當年 jQuery 拆出 prop() 的理由。