Right way to use Radiobuttons - javascript

I'm confused about which is the right way to use radiobuttons. Let's say i have a group of 3 radiobuttons : if all of them have the same id / name, it will work properly , only one can be checked :
<label for="input-rb1" ></label><input class="radio-input" type="radio" id="input-rb1" name="input-rb1"><label for="input-rb1" class="radio-label">First radiobutton</label>
<label for="input-rb1" ></label><input class="radio-input" type="radio" id="input-rb1" name="input-rb1"><label for="input-rb1" class="radio-label">Second radiobutton</label>
<label for="input-rb1" ></label><input class="radio-input" type="radio" id="input-rb1" name="input-rb1"><label for="input-rb1" class="radio-label">Third radiobutton</label>
The problem about this approach is i don't know how to identify which one is checked, because all of them have the same name / id.
The other way would use different names / ids :
<label for="input-rb1" ></label><input class="radio-input" type="radio" id="input-rb1" name="input-rb1"><label for="input-rb1" class="radio-label">First radiobutton</label>
<label for="input-rb2" ></label><input class="radio-input" type="radio" id="input-rb1" name="input-rb2"><label for="input-rb2" class="radio-label">Second radiobutton</label>
<label for="input-rb3" ></label><input class="radio-input" type="radio" id="input-rb1" name="input-rb3"><label for="input-rb3" class="radio-label">Third radiobutton</label>
This way i know how to use JQuery to know which is checked, but it will allow the user to select multiple radios, like it was checkboxes...
How to solve this puzzle ?
Thanks !

An id is a keyword that can be used to find a specific element on a page.
<input type="radio" id="radio1">one
<input type="radio" id="radio2">two
<input type="radio" id="radio1">one
<input type="radio" id="radio2">two
You'll notice the above snippet allows you to select both radio buttons. There's nothing joining them together and the Browser can't assume they're connected.
A name is used to determine a value from an input field - or in the case of radio buttons - a single value from multiple input fields. It joins the radio buttons together to say "Hey, only allow one of you to be checked! That's the value we're going with!"
<input type="radio" name="radio_group">one
<input type="radio" name="radio_group">two
<input type="radio" name="radio_group">one
<input type="radio" name="radio_group">two
Notice that there are no ids in the above code. id and name are not interchangeable. They are completely separate attributes aimed to do two completely different things.
The other answers use JQuery and that's all well and good, but I think it's important to give a vanilla JS example as well.
document.querySelectorAll("input[name='r_group']").forEach((radio) => {
if (radio.checked) {
//do whatever
}
});
document.querySelectorAll("input[name='r_group']").forEach((radio) => {
radio.addEventListener("change", () => {
if (radio.checked) alert(radio.value);
});
});
<input id="radio1" type="radio" name="r_group" value="one">one
<input id="radio2" type="radio" name="r_group" value="two">two
<input id="radio3" type="radio" name="r_group" value="three">three

Only name of radio buttons should be same, id is an unique attribute in elements. You should use different ids and also you can use value attribute to assign values. Code is given below
<form action="">
<input type="radio" id="1" name="gender" value="male"> Male<br>
<input type="radio" id="2" name="gender" value="female"> Female<br>
</form>
You can use jQuery to get selected radio button value as follow
$("input[type='radio']").on('change', function () {
var selectedValue = $("input[name='gender']:checked").val();
if (selectedValue) {
alert(selectedValue);
}
});

First, the values for "id" should be unique to each element. The name attribute can (and should) be the same for all elements in the group.
Then, to get the value of the checked radio use:
$('input[name=name_of_your_radiobutton]:checked').val();

The second approach is wrong, name in radio buttons is used to group them in same class, only one of them can be selected.
Just use the following script-
$('input[name="input-rb1"]:checked').val();
Avoid using hyphen - in javascript instead use _ if possible

Related

Radio buttons returning final value in list

relatively new to both JS (apps script) and HTML
Please can you help- I have a form that is generally submitting perfectly (text boxes, date box) but the radio is always selecting the final value. Here is the HTML (bootstrap CSS, got from a template site) and JS to gather the data at the end-
<div class="col-md-6">
<label class="radio-inline" for="ST0">
<input type="radio" name="STRating" id="ST0" value="1">
1
</label>
<label class="radio-inline" for="ST1">
<input type="radio" name="STRating" id="ST1" value="2">
2
</label>
<label class="radio-inline" for="ST2">
<input type="radio" name="STRating" id="ST2" value="3" checked="checked">
3
</label>
<label class="radio-inline" for="ST S">
<input type="radio" name="STRating" id="ST3" value="4">
4
</label>
<label class="radio-inline" for="ST4">
<input type="radio" name="STRating" id="ST4" value="5">
5
</label>
And the Apps script
function testing143(){
var form = document.getElementById("myForm").elements;
var obj ={};
for(var i = 0 ; i < form.length ; i++){
var item = form.item(i);
obj[item.name] = item.value;
}
google.script.run.withSuccessHandler(success).testing143(obj);
All the five elements of the radio buttons share the same name, hence your code reassigns five times a value to obj['STRating'], and the last assignment (5) is what you get.
Instead of doing the unconditional assignment
obj[item.name] = item.value;
You should condition the assignment only for the checked button, like that:
if (item.checked) obj[item.name] = item.value;
This way you still pass through all five buttons, but you memorize only the value of the checked one.
You are using a named array and you have five elements with the same name "STRating". The last loop will set it to "5".
I think you need more like the selected value. More Infos: How to get the selected radio button’s value?

Dynamically adding sets of radio inputs

So I have dynamic form that I create and there could be multiple sets of radio inputs they all do have the same name Release[] but I do not know how to group the properly now if you will add 4 sets of those radio inputs you will be only able to select 1 from all of them
$('a#AddChampion').on('click', function () {
$('div#ChampionInput').append(
'<input type="radio" name="Release[]" value="New">New\
<input type="radio" name="Release[]" value="Rework">Rework\
<input type="radio" name="Release[]" value="None" checked>None\
');
});
Yes if you intend to use the same name only one output can be obtained. If you want to collect them separately you will have to use separate names.
E.g.
For two groups of ReleaseGrp1 and ReleaseGrp2
<input type="radio" name="ReleaseGrp1" value="New">New
<input type="radio" name="ReleaseGrp1" value="Rework">Rework
<input type="radio" name="ReleaseGrp1" value="None" checked>None
<input type="radio" name="ReleaseGrp2" value="New">New
<input type="radio" name="ReleaseGrp2" value="Rework">Rework
<input type="radio" name="ReleaseGrp2" value="None" checked>None

As for all the tags input with the specified attribute to set, for example, attribute checked = false?

Put tags input type = "radio" with its attribute data-group:
<input type="radio" id="id1" data-group="group1">
<input type="radio" id="id2" data-group="group1"><br>
<input type="radio" id="id3" data-group="group2">
<input type="radio" id="id4" data-group="group2"><br>
How at all elements of input type="radio", which is data-group "group1", set the checked=false?
You can use the attribute selector:
$('input[type="radio"][data-group="group1"]').prop('checked', false);
Or filter():
$('input[type="radio"]').filter(function() {
return $(this).data('group') == 'group1';
}).prop('checked', false);
The best way to group radio buttons is to use the name attribute; the browser will then group them together for you, unchecking others when you check another member of the same group. That's the purpose of input[type=radio]:
<input type="radio" id="id1" name="group1">
<input type="radio" id="id2" name="group1"><br>
<input type="radio" id="id3" name="group2">
<input type="radio" id="id4" name="group2"><br>
And if you wanted to make all of the name="group1" ones unchecked, then:
$("input[type=radio][name=group1]").prop("checked", false);
But if you want to use your current structure, and you're asking how to set them all unchecked, then you can use an attribute selector:
$("input[type=radio][data-group=group1]").prop("checked", false);

jQuery validate, radio button group, nesting issue

I am trying to add a custom method to validate a group of radio buttons, using v1.9 of the jQuery validate plugin.
Contrary to this post, it is possible to have the same name attribute for radio button inputs, as long as any class rules are only applied to one of the inputs. jQuery validate then treats your input group as a single input.
This works when your inputs are children of a common parent, ie
<input type="radio" name="radiogroup" value="1" class="input-shipping" checked="checked">
<input type="radio" name="radiogroup" value="2">
<input type="radio" name="radiogroup" value="3">
<input type="radio" name="radiogroup" value="4">
But as soon as the html structure changes, the validation rules are not applied:
<div class="form-row">
<input type="radio" name="radiogroup" value="1" class="input-shipping" checked="checked">
</div>
<div class="form-row">
<input type="radio" name="radiogroup" value="2">
</div>
<div class="form-row">
<input type="radio" name="radiogroup" value="3">
</div>
<div class="form-row">
<input type="radio" name="radiogroup" value="4">
</div>
Is anyone aware of a workaround for this issue? Class rules are added as follows:
$.validator.addClassRules({
"input-shipping" : {
required: true,
dateselected: true
}
});
$.validator.addMethod("dateselected", function(value, element) {
console.log(element);
});
The reason the validation rule was not being called was that custom radio buttons were used, which set the CSS display value of inputs to none, and pseudo elements were styled up in place of the original inputs.
Once this was changed to visibility:hidden; the validator seemed to pick up the rule OK.
To create a custom method based on the value of the selected input, a further level of filtering was needed:
$.validator.addMethod("dateselected", function(value, element) {
var radios = $('input[name='+element.name+']'),
val = radios.filter(':checked')[0].value;
console.log(val);
});

Find name of the radio button that is checked

My page has about 25 radio button groups. When a radio button is selected in a group, I want to perform an action Specific to that group, and so need the NAME attrib of the radio group.
Take this HTML for example :
<div id="stackExchange">
<input type="radio" name="sofu_group" value="Stack Overflow">
<input type="radio" name="sofu_group" value="Meta Stack Overflow">
<input type="radio" name="sofu_group" value="Server Fault">
<input type="radio" name="sofu_group" value="Super User">
</div>
<!-- In no particular order - don't want to start a flame war ;) -->
If you wanted to deduce what group the clicked radio button belongs to you could use something like this :
// jQuery ver 1.7+
$("#stackExchange input:radio").on('click',function(){
var groupName = $(this).attr('name');
var groupElements = $(this).parent().find(":radio[name='"+groupName+"']");
});
Lets see whats going on here :
$("#stackExchange input:radio") - this selector will find us all of the input radio elements that are decendants of the #stackExchange element using the :radio selector. (Link to docs).
$(this).attr('name') - here is where we extract the name attribute of the selected radio element. (In our example - this becomes sofu_group).
$(this).parent() - In this case the variable $(this) refers to the radio element that was clicked - so we are selecting its parent - the #stackExchange element.
parent().find(":radio[name='"+groupName+"']") - this line will find all of the radio buttons held within the element that have a name attribute set to 'sofu_group'.
In the example - the variable $(this) refers to the radio element that was clicked.
This might give you some hint
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.cgi" method="POST">
<div align="center"><br>
<input type="radio" name="group1" value="Milk"> Milk<br>
<input type="radio" name="group1" value="Butter" checked> Butter<br>
<input type="radio" name="group1" value="Cheese"> Cheese
<hr>
<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
<input type="radio" name="group2" value="Wine" checked> Wine<br>
</div>
</form>
</body>
</html>
call document.getElementsByName("group1").items(0).<propertyname>or<function>

Categories