【问题标题】:Show alert when radio button value is selected选择单选按钮值时显示警报
【发布时间】:2015-07-28 16:34:42
【问题描述】:
<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>

我试图在选择单选值时显示警报...但是这种方法似乎不起作用。

我是不是做错了什么?

【问题讨论】:

  • 如果你使用 jquery,你只需要 ($(this).val()) 和一个点击函数 -- 演示 -- jsfiddle.net/z66fbof2
  • @TasosAnastasiou 我可以重定向到一个网址吗?
  • 来自我假设的电台选择??是的,将值更改为“somesite.com”并查看下面的答案

标签: javascript jquery if-statement radio-button


【解决方案1】:

您应该使用change 事件而不是click 事件。 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>

【讨论】:

  • 似乎无法让它工作,这就是我所拥有的:&lt;script type="text/javascript"&gt; $("#language_radio 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(); }); &lt;/script&gt;
  • &lt;div id="language-container"&gt; &lt;form id="language_radio"&gt; &lt;input type="radio" name="choice" value="V1" id="v1"&gt; &lt;label for="v1"&gt;V1&lt;/label&gt; &lt;input type="radio" name="choice" value="V2" id="v2"&gt; &lt;label for="v2"&gt;V2&lt;/label&gt; &lt;input type="radio" name="choice" value="V3" id="v3"&gt; &lt;label for="v3"&gt;V3&lt;/label&gt; &lt;input type="radio" name="choice" value="V4" id="v4"&gt; &lt;label for="v4"&gt;V4&lt;/label&gt; &lt;/form&gt; &lt;/div&gt;
  • 脚本标签应该在您的language-container div(及其所有内容)之后,是这样吗?
  • 是的,IMG
  • 哈哈,好吧,很高兴它终于成功了:)没问题。
猜你喜欢
  • 2021-05-07
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多