1,radio分组
只要name一样,就是一组的,即一组中只能选择一个,如下:
代码如下:
group1:
radio1
radio2
radio3
group2:
radio4
radio5
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值以','分隔 返回一个数组
Bootstrap框架中radio设置值
Bootstrap中的radio设置值不能像我们平常给普通radio赋值那样,因为无效. 我们用Bootstrap框架里的radio组件,代码: