【JavaScript】select、radio、checkbox 选中与获取值

checkbox

判断是否选中

<body>
    <input type="checkbox" id="oCh">
    <script>
    //jQuery
        $('#oCh').is(':checked') //false、true
        $('#oCh').prop('checked') //false、true
        $('#oCh').attr('checked') //jQ版本1.6+返回 undefined、checked
        $('#oCh').attr('checked') //jQ版本1.6之前返回 false、true
    </script>
    <script>
      //原生js
          var oCh = document.getElementById('oCh');
          if(oCh.checked) //返回false、true
    </script>
</body>

设置、取消选中

$('#oCh').attr('checked',true) //取消 false
$('#oCh').removeAttr('checked')
$('#oCh').prop('checked',true) //取消 false
<script>
  //原生js
      var oCh = document.getElementById('oCh');
      oCh.checked = true
</script>

radio

判断是否选中

<div>
    <input type="radio" id="oCh" name="age" value="01">
    <input type="radio" id="oCh2" name="age" value="02">
</div>
<script>
    $('input[name="age"]:checked').val() //01、02、undefined
    $('input[name="age"]').attr('checked') //checked、undefined
    $('input[name="age"]:checked').length //0、1
</script>
<script>
      //原生js
          var oCh = document.getElementById('oCh');
          if(oCh.checked) //返回false、true
</script>

设置选中

$('input[name="age"]').eq(0).attr('checked','true') //通过eq
$('input[name="age"][value="022"]').attr('checked','true') //通过value
<script>
  //原生js
      var oCh = document.getElementById('oCh');
      oCh.checked = true
</script>

select

获取选中的值

<select id="oCh">
    <option>01</option>
    <option>02</option>
</select>
<script>
    $('#oCh').val() //01
    $('#oCh option:selected').text() //01
    $('#oCh').find('option:selected').text() //01
</script>

设置选中

<script>
    $('#oCh').val('02') //设置02选中
    $('#oCh').find('option:contains("02")').attr('selected',true)
</script>

猜你喜欢

转载自blog.csdn.net/meichaoWen/article/details/112725903
今日推荐