Niel Sinel
Niel Sinel

Reputation: 291

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

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)? What is the best DOM event to use on it?

Upvotes: 1

Views: 3210

Answers (2)

NawaMan
NawaMan

Reputation: 25687

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

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

Upvotes: 4

Ritesh Kashyap
Ritesh Kashyap

Reputation: 394

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. 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. FF/chrome/others may fire the event without focus changing, but I believe IE is actually doing it right in this case.

Courtesy : @lincolnk

link : Stackoverflow

Upvotes: 0

Related Questions