简体   繁体   中英

Show alert when radio button value is selected

<script type="text/javascript">
function radio_form(){
   var selectvalue = $('input[name=choice]:checked', '#radio_form').val();

if(selectvalue == "V1"){
   alert('Value 1');
   return true;
}else if(selectvalue == "V2"){
   alert('Value 2');
   return true;
}else if(selectvalue == 'V3'){
   alert('Value 3');
   return true;
}else if(selectvalue == 'V4'){
   alert('Value 4');
   return true;
}
return false;
};
</script>

<form id="radio_form">
  <input type="radio" onclick="radio_form()"  name="choice" value="V1"> 
  <input type="radio" onclick="radio_form()" name="choice" value="V2"> 
  <input type="radio" onclick="radio_form()" name="choice" value="V3">
  <input type="radio" onclick="radio_form()" name="choice" value="V4"> 
</form>

I am trying to show an alert when a radio value is selected...however this approach doesn't seem to work.

Am I doing something wrong?

You should use the change event instead of the click event. The change event will only trigger when the value of the checkboxes changes, the click event will trigger everytime you click on them, even if you click on the one that is already selected. Also, instead of using inline events, just use a jQuery selector to attach the event to all of the checkboxes.

 $("#radio_form input[type=radio]").change(function () { alert( 'Redirecting to: .../' + $(this).val() ); // This will redirect to the value, relative to the current path location.href = $(this).val(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="radio_form"> <input type="radio" name="choice" value="V1"> <input type="radio" name="choice" value="V2"> <input type="radio" name="choice" value="V3"> <input type="radio" name="choice" value="V4"> </form> 

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.

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