zoukankan      html  css  js  c++  java
  • 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值以','分隔 返回一个数组
     
  • 相关阅读:
    ASP.Net Cms
    GetHashCode函数所存在的陷阱
    NH的系统架构
    Icomparable<T> 和 Icomparaer<T> 实现顺序关系
    《创业法典》:用流程图告诉你如何创业
    创业之前,网站先行
    杨卫华:新浪微博的架构发展历程
    技术开发人员为什么会无奈苦逼?
    使用面向对象的、完整的单点登录功能
    SilverLight之我见
  • 原文地址:https://www.cnblogs.com/franson-2016/p/5607279.html
Copyright © 2011-2022 走看看