DIV CSS 佈局教程網

jQuery 取得 Radio 與 CheckBox 選中值的完整語法
編輯:JQuery特效代碼     

處理單選與多選按鈕的值,是表單開發的基礎功。以下把常用語法整理清楚,方便隨時查閱。

Radio 的操作

$("input[name='radio_name'][checked]").val(); //取得被選中 Radio 的 Value 值

搭配焦點事件使用:

$("#text_id").focus(function(){//當 text_id 取得焦點時觸發
$("#text_id").blur(function(){//當 text_id 失去焦點時觸發
$("#text_id").select(); //使文字框的 Value 值進入選中狀態

依 Value 值設定某個 Radio 為選中:

$("input[name='radio_name'][value='要選中Radio的Value值']").attr("checked",true);

CheckBox 的操作

選取所有被勾選的 CheckBox 元素集合(若要取值需遍歷這個集合):

$("input[name='checkbox_name'][checked]");

遍歷被選中的 CheckBox 並收集 Value 值:

$($("input[name='checkbox_name'][checked]")).each(function(){arrChk+=this.value +',';});

取得單一 CheckBox 的狀態(是否被選中,回傳 true/false):

$("#checkbox_id").attr("checked");

設定某個 CheckBox 為選中:

$("#checkbox_id").attr("checked",true);

設定某個 CheckBox 為不選中:

$("#checkbox_id").attr("checked",false);

把文字框的值以逗號分隔成陣列:

$("#text_id").val().split(",");

由於 Radio 只能單選,用 val() 直接取值即可;而 CheckBox 可以多選,因此取得的是一個集合,需要用 each 逐一遍歷收集,這兩者的差異要多加留意。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved