简体   繁体   English

触发按钮选择单选按钮时单击

[英]Trigger Button Click when Radio button is selected

I have two radio buttons, when I select one of radio button (ex: id = one), and click button will be show alert ("one"). 我有两个单选按钮,当我选择一个单选按钮(例如:id =一个)时,单击按钮将显示警报(“一个”)。 here is my code 这是我的代码

<input type="radio" name="test" value="one" id="one">one
<input type="radio" name="test" value="two" id="two">two
<button id="click">Click</button>

and my JS 和我的JS

$("#click").click(function(){
  if($('input[type="radio"]').attr('id') == 'one'){
    alert ("one")
  } else{
    alert("two")
  }
})

My question is why alert two is not show? 我的问题是为什么警报二不显示? any body help? 有什么身体帮助吗? thank you http://jsfiddle.net/dedi_wibisono17/gydrw291/10/ 谢谢你http://jsfiddle.net/dedi_wibisono17/gydrw291/10/

See the docs on .attr : 请参阅.attr的文档

The .attr() method gets the attribute value for only the first element in the matched set. .attr()方法仅获取匹配集中第一个元素的属性值。 To get the value for each element individually, use a looping construct... 要单独获取每个元素的值,请使用循环构造...

Because your selector 因为您的选择器

input[type="radio"]

will always return a collection that contains the #one element in front, your if statement will always evaluate to true . 将始终返回在前面包含#one元素的集合,您的if语句将始终求值为true

To fix it, have your selector string select only the radio button that's selected - so, use the :checked psuedo-selector as well: 为了解决这个问题,有你的选择字符串只选择选中后的单选按钮-所以,使用:checked伪选择器以及:

 $("#click").click(function() { if ($('input[type="radio"]:checked').attr('id') == 'one') { alert("one") } else { alert("two") } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="test" value="one" id="one">one <input type="radio" name="test" value="two" id="two">two <button id="click">Click</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM