选择单选按钮值时显示警报

时间:2015-05-16 23:24:32

标签: javascript jquery if-statement radio-button

<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>

我正在尝试在选择无线电值时显示警告......但是这种方法似乎无法正常工作。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

您应该使用change事件而不是click事件。只有当复选框的值发生更改时,才会触发更改事件,每次单击它们时都会触发单击事件,即使您单击已选中的事件也是如此。此外,不要使用内联事件,只需使用jQuery选择器将事件附加到所有复选框。

$("#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>

相关问题