Reputation: 77
Sorry for the noob question, but I'm starting to learn Jquery, and I have followed what seems to be a very straightforward tiny code that displays an alert box. However, when I try it on codepen or my wordpress site, it doesn't work. Here is HTML
$(document).ready(function(){
$('#my_radio_box').change(function(){
alert('Radio Box has been changed!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_radio_box">
<input type="radio" name="my_options" value="option 1"> Option 1
<input type="radio" name="my_options" value="option 2"> Option 2
<input type="radio" name="my_options" value="option 3"> Option 3
</form>
What am I missing here?
Upvotes: 1
Views: 213
Reputation: 68933
You can use the name
attribute in the selector like:
$(':radio[name=my_options]').change(function(){
Working Code Example:
$(document).ready(function(){
$(':radio[name=my_options]').change(function(){
alert('Radio Box has been changed to '+ this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_radio_box">
<input type="radio" name="my_options" value="option 1"> Option 1
<input type="radio" name="my_options" value="option 2"> Option 2
<input type="radio" name="my_options" value="option 3"> Option 3
</form>
Upvotes: 1
Reputation: 3177
$(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
alert($(this).val());
}
});
});
If you give your radio buttons a class then you can replace the code $('input[type="radio"]')
with $('.someclass')
Upvotes: 0