Reputation: 85
I'm trying to figure out how to use Jquery to alert "Text" only when the "Yes" radio button is clicked.
The problem with my code, is that the alert shows also when the "No" button is clicked.
As you see, I also added a checkbox with a comment, to make it clear.
If you can, please help me, how to fix this?
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($('input[name=one][value =yes]:checked')) {
alert("Text");
}
if($('input[name=two][value =no]:checked')) {
// alert("Text");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Show text?</p>
<input type="radio" name="one" value="yes">Yes
<input type="radio" name="one" value="no">No
<p>Do somthing Else</p>
<input type="checkbox" name="two" value="no">No
Upvotes: 2
Views: 57
Reputation: 1156
Try this..
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($('input:radio[name="one"]:checked').val() =="yes") {
alert("Text");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Show text?</p>
<input type="radio" name="one" value="yes">Yes
<input type="radio" name="one" value="no">No
<p>Do somthing Else</p>
<input type="checkbox" name="two" value="no">No
Upvotes: 0
Reputation: 337560
You need to use the this
keyword to retrieve the value
from the radio which raised the event. Then you can simply read its value in the if
condition, like this:
$(document).ready(function() {
$('input[type="radio"]').change(function() {
if ($(this).val() == 'yes') {
console.log("Text");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Show text?</p>
<input type="radio" name="one" value="yes">Yes
<input type="radio" name="one" value="no">No
<p>Do somthing Else</p>
<input type="checkbox" name="two" value="no">No
Note the use of the change
event over click
for accessibility reasons, and also console.log()
instead of alert()
for debugging.
Upvotes: 3