I have two radio buttons, when I select one of radio button (ex: id = one), and click button will be show alert ("one"). 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
$("#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/
See the docs on .attr
:
The .attr() method gets the attribute value for only the first element in the matched set. 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
.
To fix it, have your selector string select only the radio button that's selected - so, use the :checked
psuedo-selector as well:
$("#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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.