本文實例講述了JQuery控制Radio選中方法。分享給大家供大家參考。具體如下:
方法1:
$(function () { $("#spanNan").click(function () { $("#Radio1").attr("checked", true); $("#Radio2").attr("checked", false); }); $("#spanNv").click(function () { $("#Radio2").attr("checked", true); $("#Radio1").attr("checked", false); });})
方法2:(簡單方法)
$(function () { $("#spanNan").click(function () { //$("#Radio1").attr("checked", true); //$("#Radio2").attr("checked", false); $("#Radio1").click(); }); $("#spanNv").click(function () { //$("#Radio2").attr("checked", true); //$("#Radio1").attr("checked", false); $("#Radio2").click(); });})
<input id="Radio2" type="radio" name="sex"/><label for="Radio2">女</label>
總結:
HTML的Radio控件若要實現單選,比如本例中男女的選擇,需要給Radio添加name屬性,且值相同;例:name=“sex”。
默認選上radio:
jQuery(document).ready(function(){ $("input[name=targetBlank]:eq(0)").attr("checked",'checked'); $("input[name=status]:eq(0)").attr("checked",'checked');});
使用jquery獲取radio的值,最重要的是掌握jquery選擇器的使用,在一個表單中我們通常是要獲取被選中的那個radio項的值,所以要加checked來篩選,比如有以下的一些radio項:
1.<input type="radio" name="testradio" value="jquery獲取radio的值" />jquery獲取radio的值
2.<input type="radio" name="testradio" value="jquery獲取checkbox的值" />jquery獲取checkbox的值
3.<input type="radio" name="testradio" value="jquery獲取select的值" />jquery獲取select的值
要想獲取某個radio的值有以下的幾種方法,直接給出代碼:
$('input[name="testradio"]:checked').val();$('input:radio:checked').val();$('input[@name="testradio"][checked]');$('input[name="testradio"]').filter(':checked');
差不多挺全的了,如果我們要遍歷name為testradio的所有radio呢,代碼如下
$('input[name="testradio"]').each(function(){alert(this.value);});
如果要取具體某個radio的值,比如第二個radio的值,這樣寫
<script type="text/javascript">$(document).ready(function(){ $("input[@type=radio][name=sex][@value=1]").attr("checked",true);}); </script>
您的性別:
<input type="radio" name="sex" value="1" <s:if test="user.sex==1">checked</s:if>/>男 <input type="radio" name="sex" value="0" <s:if test="user.sex==0">checked</s:if>/>女
希望本文所述對大家的jQuery程序設計有所幫助。
新聞熱點
疑難解答