简体   繁体   English

选择单选按钮后,如何根据所选单选按钮显示输出?

[英]How to display an output depending on the selected radio button after selecting a radio button?

How to display something on <div> or <label> after selecting a specific radio button, for example is I have a group of radio button 如何在选择特定的单选按钮后在<div><label>上显示某些内容,例如我有一组单选按钮

Interest Value
o 3%
o 5%
o 7%

Amount: 1,450.00

The value of the amount will change depending on the selected radio button. 金额的值将根据所选的单选按钮而改变。 What is the correct method to do this on javascript (without jquery)? 在javascript(没有jquery)上执行此操作的正确方法是什么? What is the best DOM event to use on it? 什么是最好的DOM事件?

You can just listen to its click event. 你可以只听它的点击事件。

See the code here on jsfiddle shamlessly copied from OnChange event handler for radio button (INPUT type="radio") doesn't work as one value 这里看到 jsfiddle中的代码OnChange 上无意中复制了单选按钮的事件处理程序(INPUT type =“radio”)不能作为一个值工作

<form name="myForm">
    <input type="radio" name="myRadios"  value="3" >3%</value>
    <input type="radio" name="myRadios"  value="5" >5%</value>
    <input type="radio" name="myRadios"  value="7" >7%</value>
</form>
Amount: <span id="amount"></span>

<script>
var amountField = document.getElementById('amount');
var rad = document.myForm.myRadios;
var prev = null;
for(var i = 0; i < rad.length; i++) {
    rad[i].onclick = function() {
        console.log(this.value);
        if(this !== prev) {
            prev = this;
            amountField.textContent = 1000+1000*this.value/100;
        }
    };
}
</script>

It depends when you want to be informed of the event. 这取决于您何时想要了解该事件。

If you want to know immediately, go with click. 如果您想立即了解,请点击。 IE updates the state of checked before the handler function is called, and I think the other browsers do as well. IE在调用处理函数之前更新了checked状态,我认为其他浏览器也可以。 You may want to double check this fact. 您可能想要仔细检查这一事实。

If you only need to know before something else happens, you can use change. 如果您只是在事情发生之前需要知道,您可以使用更改。 IE will not fire the change event until the selected radio button loses focus. 在选定的单选按钮失去焦点之前,IE不会触发更改事件。 FF/chrome/others may fire the event without focus changing, but I believe IE is actually doing it right in this case. FF / chrome /其他人可能会在不改变焦点的情况下触发事件,但我相信IE在这种情况下实际上是正确的。

Courtesy : @lincolnk 礼貌:@lincolnk

link : Stackoverflow 链接: Stackoverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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