How do I loop through a radio buttons group without a form in JavaScript or jQuery?
When focus moves to the group in which a radio button is selected, pressing Tab and Shift+Tab keys move focus to the radio button that is checked. Up Arrow and Down Arrow keys move focus and selection. Up Arrow key press moves focus and selection forward through the radio buttons in the group.
You group radio buttons by drawing them inside a container such as a Panel control, a GroupBox control, or a form. All radio buttons that are added directly to a form become one group. To add separate groups, you must place them inside panels or group boxes.
Answer: To make a radio button not selectable, in the button's INPUT tag you can use an onclick event handler like this: <INPUT type="radio" name="myButton" value="theValue" onclick="this. checked=false; alert('Sorry, this option is not available!') ">
Only one radio button in a given group can be selected at the same time.
What about something like this? (using jQuery):
$('input:radio').each(function() { if($(this).is(':checked')) { // You have a checked radio button here... } else { // Or an unchecked one here... } });
You can also loop through all the checked radio buttons like this, if you prefer:
$('input:radio:checked').each(function() { // Iterate through all checked radio buttons });
...in case someone wants to do this without jQuery (since it was part of the question):
I'm not sure what you mean by without a form. If you mean you don't want to pass the form element to a javascript function, you could do it like this:
for (var i = 0; i < document.form_name.radio_name.length; i++) { if (document.form_name.radio_name[i].checked) { // ... } }
If you mean without a form as in you have no form node, you could wrap them in a span (or a div) and use code like this:
var span = document.getElementById("span_id"); var inputs = span.getElementsByTagName("input"); for (var i = 0; i < inputs.length; ++i) { if (inputs[i].checked) { // ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With