Reputation: 11917
I have found a problem with using radio buttons with bootstrap, and getting javascript to query the selection of the radio button. The problem is that when the radio button selection is changed, onclick
events associated with the buttons read the previous selection, not the current one.
This is a MWE I have been able to create (turn on Console to see the problem):
https://jsbin.com/pasujeqeli/edit?html,output
Clicking on 'Zero' logs True to console. Clicking 'Zero' again logs False to console. In fact, the log to console is now one click 'behind' the actual state of the radio buttons.
I have been able to recreate this bug without bootstrap.css, by clicking not on the radio button itself but by clicking the label associated with the radio button.
It seems that when clicking the label, the onclick
method is called before the radio button is updated. On the other hand, when clicking the radio button itself, the onclick
method is called after the radio button is updated.
My question is: How can I change the js or html to ensure I can always query the current state of the radio buttons?
Upvotes: 0
Views: 230
Reputation: 3970
There's an easy and efficient way to solve this and it's by adding the function under the onchange
event for each input like the following
<label class="btn btn-primary active">
<input type="radio" onchange="checkform()" name="number" checked="" id="one" value="One" >One
</label>
The onchange
event will be fired after the radio button is change not before like what's happening with the onclick
event
Upvotes: 1