操作表單是前端開發的日常,這裡整理了一系列 jQuery 表單取值的常用寫法,涵蓋下拉選單、單選框、複選框、文字框等,方便隨查隨用。
先來看一個禁用按鈕並提交表單的範例:
$(document).ready(function(){
$("#save").click(function(){
$("#save").attr("disabled",true);//設為不可用
$("#form1")[0].submit();//提交表單
});
});
$("#select option[selected]").text();
$("#select option:selected").text();
$("#select").val();//取值
$("#select").val("value");//設置
$("#select").empty();
$("#select").html("");
$('<option value="1">1</option>').appendto($("#select"));
$("#select").append('<option value="1">1</option>');
$("#id[checked]").val();
$("#id[value=val]").attr("checked",true);//選擇
$("#id[value=val]").removeattr("checked");//取消選擇
$("input[type=checkbox][checked]").each(function(){
alert($(this).val());
})
if($("#id").attr("checked")){}//判斷選中
if($("#id").attr("checked")==undefined){}//判斷未選中
$("#id").attr("disabled",false);//設為可用
$("#id").attr("disabled",true);//設為不可用
if($("#id").attr("disabled")){}//判斷不可用
if($("#id").attr("disabled")==undefined){}//判斷可用
取值:var textval = $("#text_id").val();
清除內容:$("#txt").attr("value","");
填充內容:$("#txt").attr("value",'123');
取值:var selectval = $('#sell').val();
添加新項:$("<option value='test'>test</option>").appendTo("#select_id");
清空下拉框:$("#select_id").empty();
以上代碼幾乎涵蓋了日常表單操作的所有情境,建議收藏起來作為開發時的速查表。