如何使用jQuery选择单选按钮

一个使用jQuery动态选择单选按钮的简单示例。

单选按钮组,名称为“ sex”。

<input type="radio" name="sex" value="Male">Male</input>
<input type="radio" name="sex" value="Female">Female</input>
<input type="radio" name="sex" value="Unknown">Unknown</input>

1.显示选定的单选按钮值。

$('input:radio[name=sex]:checked').val();

2.选择一个单选按钮(男性)。
单选按钮从0开始,因此'Male'='0','Female'='1'和'Unknown'='2'。

$('input:radio[name=sex]:nth(0)').attr('checked',true);
or
$('input:radio[name=sex]')[0].checked = true;

3.选择单选按钮(女)。

$('input:radio[name=sex]:nth(1)').attr('checked',true);
or
$('input:radio[name=sex]')[1].checked = true;

4.选择单选按钮(未知)。

$('input:radio[name=sex]:nth(2)').attr('checked',true);
or
$('input:radio[name=sex]')[2].checked = true;

5.重置选定的单选按钮。

$('input:radio[name=sex]').attr('checked',false);

jQuery选择单选按钮示例

<html>
<head>
<title>jQuery select a radio button example</title>
 
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

</head>

<body>

<h1>jQuery select a radio button example</h1>

<script type="text/javascript">

  $(document).ready(function(){

    $("#isSelect").click(function () {
		
	alert($('input:radio[name=sex]:checked').val());
			
    });
	
    $("#selectMale").click(function () {
		
	$('input:radio[name=sex]:nth(0)').attr('checked',true);
	//$('input:radio[name=sex]')[0].checked = true;

    });
	
    $("#selectFemale").click(function () {
		
	$('input:radio[name=sex]:nth(1)').attr('checked',true);
	//$('input:radio[name=sex]')[1].checked = true;
			
    });
	
    $("#selectUnknown").click(function () {
		
	$('input:radio[name=sex]:nth(2)').attr('checked',true);
	//$('input:radio[name=sex]')[2].checked = true;

    });
	
    $("#reset").click(function () {
		
	$('input:radio[name=sex]').attr('checked',false);
	
    });
		
  });
</script>
</head><body>

<input type="radio" name="sex" value="Male">Male</input>
<input type="radio" name="sex" value="Female">Female</input>
<input type="radio" name="sex" value="Unknown">Unknown</input>

<br/>
<br/>
<br/>

<input type='button' value='Display Selected' id='isSelect'>
<input type='button' value='Select Male' id='selectMale'>
<input type='button' value='Select Female' id='selectFemale'>
<input type='button' value='Select Unknown' id='selectUnknown'>
<input type='button' value='Reset' id='reset'>

</body>
</html>

翻译自: https://mkyong.com/jquery/how-to-select-a-radio-button-with-jquery/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值