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值以','分隔 返回一个数组
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值