Theo E
Theo E

Reputation: 77

How do I get an alert box in jquery?

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

Answers (2)

Mamun
Mamun

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

Mile Mijatović
Mile Mijatović

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

Related Questions