html中radio,checkbox值的獲取、賦值、注冊事件


1,radio分組 

只要name一樣,就是一組的,即一組中只能選擇一個,如下: 

代碼如下:

<span>group1:</span> 
<input type="radio" id="radio1" checked="checked" name="group1" />radio1 
<input type="radio" id="radio2" name="group1" />radio2 
<input type="radio" id="radio3" name="group1" />radio3 

<span>group2:</span> 
<input type="radio" id="radio4" checked="checked" name="group2" />radio4 
<input type="radio" id="radio5" name="group2" />radio5 
<input type="radio" id="radio6" name="group2" />radio6 

 

效果如下: 
 

2,獲取選中的radio節點 

使用jquery可以很方便做到,先選擇group,然后過濾出checked的,如下: 

代碼如下:

var group1 = $("[name='group1']").filter(":checked"); 
console.log(group1.attr("id")); 

3,選中一個radio節點 


使用jquery設置checked屬性: 

 
代碼如下:

$("#radio2").attr("checked", "checked"); 

 

4,去選中一個radio節點 

移除checked屬性: 

代碼如下:

$("#radio1").removeAttr("checked"); 

 

這樣做的結果可能造成一組radio中沒有一個處於選中狀態。 

5,注冊選中去選中事件 

還是使用jquery的on函數來注冊change事件,如下: 

代碼如下:

$("[name='group1']").on("change", 
function (e) { 
console.log($(e.target).val()); 
} 
); 

 

這樣只要group1中任何一個有選中的,就會觸發函數。

附:jquery中常見的對text,radio,checkbox獲取值,賦值的操作代碼-----

//獲取單選框radio中checked的值
//方式一
var sex=$("input[name='radio_sex']:checked").attr("value");//xxxx.value 是javascript取值方式,使用jquery取值可為:$("xxxx").val()  或者  $("xxxx").attr("value")
//方式二
var sex=$("[name='radio_sex']").filter(":checked").attr("value"); 


$("#text_id").focus(function(){//code...}); //事件 當對象text_id獲取焦點時觸發
$("#text_id").blur(function(){//code...}); //事件 當對象text_id失去焦點時觸發
$("#text_id").select(); //使文本框的Vlaue值成選中狀態
$("input[name='radio_name'][value='要選中Radio的Value值'").attr("checked",true); //根據Value值設置Radio為選中狀態

 

 

jQuery獲取CheckBox選擇的Value值

//遍歷被選中CheckBox元素的集合 得到Value值
var hobby='';
//方式一
$("[name='hobby']").filter(":checked").each(function(){$(this).attr("value")+',';//可以使用this.value+',';   或者   $(this).val()+',';
});
//方式二
$("input[name='hobby']:checked").each(function(){hobby+=this.value+','});

$("#checkbox_id").attr("checked"); //獲取一個CheckBox的狀態(有沒有被選中,返回true/false)
$("#checkbox_id").attr("checked",true); //設置一個CheckBox的狀態為選中(checked=true)
$("#checkbox_id").attr("checked",false); //設置一個CheckBox的狀態為不選中(checked=false)
$("input[name='checkbox_name']").attr("checked",$("#checkbox_id").attr("checked"));//根據3,4,5條,你可以分析分析這句代碼的意思
$("#text_id").val().split(","); //將Text的Value值以','分隔 返回一個數組
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。