zoukankan      html  css  js  c++  java
  • 《jQuery判断radio、checkbox、select 是否选中和设置选中问题以及获取选中值》总结

    
    
    <form>
    <input type="radio" name="gender" id="man" value="男" /><input type="radio" name="gender" id="woman" value="女" /><br />
    <input type="checkbox" name="math" id="math"/>数学
    <input type="checkbox" name="english" id="english"/>英语
    <input type="checkbox" name="chinese" id="chinese"/>语文
    <br />
    <select id="province">
    <option value="beijing">北京</option>
    <option value="hubei">湖北省</option>
    <option value="hunan">湖南省</option>
    <option value="guangdong">广东省</option>
    </select>
    <input id="btnSubmit" type="submit" value="submit" />
    </form>

    1. 判断radio是否被选中:

    //可以通过判断radio被选中的个数长度是否为0
    var len = $('input[name="gender"]:checked').length;
    if(len){
        console.log('radio没有选择,请选择一个!');
    }
    //判断某个radio是否被选中
    if($('#man:checked').length){
        console.log('你选择了男的radio');
    }
    //或者
    if($('#man').is(':checked')){
        console.log('你选择了男的radio');
    }

    2. 设置radio选中:

    //javascript方法:
    document.getElementById("man").checked = true;
    //jQuery的prop方法
    $('#man').prop('checked', true);
    //取消选中
    $('#man').prop('checked', false);
    //不建议使用以下方法
    $('#man').attr('checked', true);

    3. 获取radio被选中的值

    $('input[name="gender"]:checked').val();
    //或者
    $('input[name="gender"][checked]').val();

    4. 判断checkbox是否被选中:

    //判断某个checkbox是否被选中,跟radio方法一样
    if($('#math:checked').length){
        console.log('你选择了数学');
    }
    //或者
    if($('input[name="math"]:checked').length){
        console.log('你选择了数学');
    }
    //或者
    if($('#math').is(':checked')){
        console.log('你选择了数学');
    }
    //还有一种方法是使用javascript
    if(document.getElementById("math").checked == true){
      console.log('你选择了数学');
    }
    //注意:网上流传的如下这种判断方法是不恰当的,与jQuery版本有关
    if($('#math').attr('checked') == true)
    if($('#math').attr('checked') == undefined)
    if($('#math').attr('checked') == 'checked')

    5. 设置checkbox选中:

    /***跟radio的方法一样***/
    //javascript方法:
    document.getElementById("math").checked = true;
    //jQuery的prop方法
    $('#math').prop('checked', true);
    //取消选中
    $('#math').prop('checked', false);
    //不建议使用以下方法
    $('#math').attr('checked', true);

    6. select的取值、选中

    //获取当前选中项的值
    
    $("#province").val();
    
    //获取当前选中项的text
    
    $("#province").find("option:selected").text();
    
    //设置value值为guangdong的项选中
    
    $("#province").val('guangdong');
    
    //设置text为广东的项选中
    
    $(".selector").find("option[text='广东']").attr("selected",true);
  • 相关阅读:
    Framework 7 日历插件改成Picker 模式
    DataTables 表格固定栏使用方法
    DIV内滚动条滚动到指定位置
    js类型转换 之 转字符串及布尔类型
    js类型转换 之 转数字类型
    UrlRewriter.dll伪静态实现二级域名泛解析
    sql server2005内存过高释放方法
    HttpContext.Current.RewritePath方法重写URL
    sql2005数据库转换成sql2000
    asp.net获取当前页面源码并生成静态页面
  • 原文地址:https://www.cnblogs.com/boliang/p/5554593.html
Copyright © 2011-2022 走看看