I'm using many radio-buttons in a xtcommerce-based-workaround. Those radiobuttons are dynamically created and given a different name for each group like this:
<input type="radio" name="id[1]" value="40">
<input type="radio" name="id[1]" value="30">
<input type="radio" name="id[1]" value="20">
<input type="radio" name="id[1]" value="10">
<input type="radio" name="id[2]" value="40">
<input type="radio" name="id[2]" value="30">
<input type="radio" name="id[2]" value="20">
<input type="radio" name="id[2]" value="10">
<input type="radio" name="id[3]" value="10">
....
Now I want to "group" those radio-buttons back together, so that I can only choose one radio-button at a time. Now by default every first radio-button of each "group" (name="id[1]", name="id[2]", etc.) is preselected and every value of each radio-button gets submitted.
I found this script here on stackoverflow to only select one radio-button:
$(document).ready(function () {
$('input[type=radio]').prop('checked', false);
$('input[type=radio]:first').prop('checked', true)
$('input[type=radio]').click(function (event) {
$('input[type=radio]').prop('checked', false);
$(this).prop('checked', true);
event.preventDefault();
});
});
Here is a fiddle of that:
This works so far, I can only select one radio-button on my page. But there is one problem as you can see in my js-fiddle too:
The first radio-button of the first group is preselected - that's ok. But if you choose another radio-button of the same group, the selection-"mark" does not change. Only if you click a radio-button of another group the chosen radio-button gets selected (found another bug in FF (EDIT: and Opera as well as IE9), the selection-mark is not shown if I choose any other radio-button; in Chrome it changes by selecting another group). If you stay in this same group, the selection doesn't change either.
On my local based installation I have got a dynamically-changing updater, which states the new price of the selected item (sorry I couldn't implement this to the fiddle). This works so far, the price gets updated even if I choose another radio-button of the same group, but as described before the selection-"mark" does not change...
Any idea for this problem?
You don't need to uncheck all radio buttons, then re-check the current one. Un-checking the previously checked button suffices.
As a side effect of this simplification, your bug is also fixed.
Just remove
event.preventDefault();
and it will work.Check this JSFIDDLE
Radio button with a different name but a single selection
Working Example : https://codepen.io/Vivekparashar/pen/wvwLwxY
JS :
HTML :
why do you have
event.preventDefault();
there....since your code inside click function is doing that.remove the
event.preventDefault();
and tryhere is the fiddle..
http://jsfiddle.net/ksZxV/1/