Javascript,通过多个条件获取元素(id和value)

时间:2014-10-27 04:01:21

标签: javascript jquery

我想问题很简单,但我无法在任何地方找到解决方案。我想检查一下单选按钮是否被选中。从here可能的解决方案:

对于这些输入

<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />

你可以简单地

if(document.getElementById('gender_Male').checked) {
  //Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
  //Female radio button is checked
}

但我的意见是这样的:

<label><input id="16" type="radio" value="14" name="Q3"></input>Yes</label>
<label><input id="16" type="radio" value="15" name="Q3"></input>No</label>

id本身并不是唯一的,只能与value结合使用...如何选中是或否?

6 个答案:

答案 0 :(得分:0)

正如@Markasoftware所说,id应始终是唯一的。但是浏览器仍然使用相同的id来解析你的html。

所以关键是你可以选择一个没有id的元素。

尝试document.querySelectorAlldocument.querySelector。这是代码:

document.querySelectorAll('input[value="14"]') // you can select all the `value='14'` inputs
document.querySelectorAll('input[name="Q3"]') // you can select all the `value='Q3'` inputs

您可以撰写这些css3选择器并实现目标。

答案 1 :(得分:0)

您可以尝试下一个选择器:

$('input#16.14').is(':checked'){ 
    //YES is checked
}
$('input#16.15').is(':checked'){ 
    //NO is checked
}

但是id应该是唯一的。

检查选择哪一个的另一种方法是使用输入名称:

$('input[name=Q3]:checked').val()

这样,如果选中“是”,您将获得14;如果选中“否”,则会获得15

答案 2 :(得分:0)

假设是/否元素是性别广播的下一个元素,您可以尝试以下内容:

$('[name="gender"]').change(function(){

  if($(this).val() == 'Male'){

    $(this).next('input[type="radio"][value="14"]').prop('checked',true);

  }else{
   //Female

  }

});

答案 3 :(得分:0)

在单选按钮上添加一个类。

$('.radioGroup').change(function(){
  if($(this).val() == 'Male'){
      ///
  } else {
      //female
  }
});

答案 4 :(得分:0)

    <html>
        <head>
            <meta charset="utf-8">

            <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
            <script src="//code.jquery.com/jquery-1.9.1.js"></script>
            <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

        </head>

        <body>
   <label><input id="16" type="radio" value="14" name="Q3"/>Yes</label>
   <label><input id="16" type="radio" value="15" name="Q3"/>No</label>

         <script type="text/javascript">
            $('input[name=Q3]').change(function () {
                if ($('input[name=Q3]:checked').length > 0) {
                    var k = $('input[name=Q3]:checked').val();
                    alert(k);
                }
            });
        </script>

        </body>
    </html>

答案 5 :(得分:0)

&#13;
&#13;
$(':radio').on('change',function() {
  if( this.checked && this.value === "14" ) {
    alert( "'Yes' was selected!" );
  } else if( this.checked && this.value === "15" ) {
    alert( "'No' was selected!" );
  }
});
    
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input id="Q3_1" type="radio" value="14" name="Q3">Yes</label>
<label><input id="Q3_2" type="radio" value="15" name="Q3">No</label>
&#13;
&#13;
&#13;