代碼測試
< form > 性別: < input type ="radio" name ="sex" value ="1" /> 男 < input type ="radio" checked ="checked" name ="sex" value ="0" /> 女 < br /> 水果: < input type ="checkbox" name ="fruit" value ="1" /> 蘋果 < input type ="checkbox" name ="fruit" value ="2" /> 香蕉 < input type ="checkbox" name ="fruit" value ="3" /> 橘子 </ form > < button onclick ="getRadioValue()" > Radio值 </ button > < button onclick ="getCheckboxValue()" > CheckBox值 </ button > < button onclick ="doAll()" > 全選 </ button > < button onclick ="doNotAll()" > 反選 </ button >
獲取Radio的值(判斷選中哪一個)ui
function getRadioValue() { // var sex = $("input[name='sex']:checked").val(); //方式一 var sex = $( " :radio:checked " ).val(); // 方式二 alert(sex); }
獲取CheckBox的值(選中狀態下,獲取值)this
function getCheckboxValue() { // var len = $("input[type=checkbox]:checked").length; var len = $( " :checkbox:checked " ).length; if (len != 0 ) { /* for(var i=0;i<len;i++) { //var thisValue = $($("input[type=checkbox]:checked")[i]).val(); var thisValue = $($(":checkbox:checked")[i]).val(); alert(thisValue); } */ $.each($( " :checkbox:checked " ), function () { alert($( this ).val()); }); } else { alert( ' 複選框沒有被選中 ' ); } }
CheckBox全選spa
function doAll() { /* $("input[type=checkbox][name=fruit]").each(function(){ jQuery(this).attr("checked", true); }); */ $( " :checkbox[name=fruit] " ).each( function () { $( this ).attr( " checked " , true ); }); }
CheckBox反選.net
function doNotAll() { /* $("input[type=checkbox][name=fruit]").each(function(){ jQuery(this).attr("checked", false); }); */ $( " :checkbox[name=fruit] " ).each( function () { jQuery( this ).attr( " checked " , false ); }); }
動態給Radio(測試) CheckBox賦值(CheckBox基本同Radio,未測試CheckBox)3d
$(document).ready( function () { // 給Rodio設置初始值(方法一) var _sex = 1 ; // 模擬後臺傳來的值 if (_sex == ' 1 ' ) { $( " input[name=sex][value=1] " ).attr( " checked " , true ); } else { $( " input[name=sex][value=0] " ).attr( " checked " , true ); } });
< form > 性別: < input type ="radio" <c:if test ="${後臺傳來的值 }==value" > checked="checked" </ c:if > name="sex" value="1" />男 <!-- 在標籤中用<c:if></c:if>判斷 --> < input type ="radio" checked ="checked" name ="sex" value ="0" /> 女 </ form >