Radio button allow multiple selections - javascript

Can the radio button be implemented like a checkbox button? I hope radio buttion can multiple selection. Do not use checkbox button!
I want the effect as follows:
[0,1,2]
function clickButton() {
var radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
console.log(radios[i].value);
break;
}
}
}
<form id="Selection">
<input type="radio" name="gender" value="0" /> Male<br>
<input type="radio" name="gender" value="1" /> Female<br>
<input type="radio" name="gender" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>

You can give different names to the radio buttons, then grab the tags by tag name and push the values to an array.
PS: The correct way is to checkboxes because they are designed to do this functionality
Working Demo
function clickButton() {
var radios = document.getElementsByTagName('input');
var checked = [];
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
checked.push(radios[i].value);
}
}
console.log(checked);
}
<form id="Selection">
<input type="radio" name="gender1" value="0" /> Male<br>
<input type="radio" name="gender2" value="1" /> Female<br>
<input type="radio" name="gender3" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>

The only way to allow this would be to have unique names. The radio button is specifically meant for single select. If you want multi-select ability, then that is what checkboxes would be for.
<form id="Selection">
<input type="radio" name="gender_male" value="0" /> Male<br>
<input type="radio" name="gender_female" value="1" /> Female<br>
<input type="radio" name="gender_other" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>

Just use different names for your radio buttons -
function clickButton() {
var radios = document.getElementsByClassName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
console.log(radios[i].value);
}
}
}
<form id="Selection">
<input type="radio" class="gender" name="genderMale" value="0" /> Male<br>
<input type="radio" class="gender" name="genderFemale" value="1" /> Female<br>
<input type="radio" class="gender" name="genderOther" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>

Related

Set hidden value based on radio button selection

Cannot find an answer:
I have searched Stack Overflow, however, despite finding lots of similar posts — and more complicated situations — I still couldn't find an answer to the issue I am trying to solve.
Here's my issue:
I have four radio buttons, and one hidden field:
<!-- My HTML Document -->
<form action="/my-doc.html" method="post">
<!-- The 4 Radio Buttons-->
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<!-- The Hidden Field -->
<input type="hidden" name="criteria" value="1">
<!-- My Submit Button -->
<input type="submit" name="action" value="Go">
</form>
What I need to do is set the value of <input type="hidden" name="criteria" value="1"> so that it is 0
Like this: <input type="hidden" name="criteria" value="0">
...but only after the user selects either the first, or second, radio button. The value of the hidden field should remain as being equal to 1 if any other radio button is selected.
How does a person do this using JavaScript?
Requirements: "Looking for a VanillaJS answer."
you can try below option
In javascript
function setValue() {
var selectedRadio = '';
var games = document.getElementsByName('game')
for (var i = 0; i < games.length; i++) {
if (games[i].checked) {
selectedRadio = games[i].value;
}
}
document.getElementById("hdnSelectedRadValue").value = (selectedRadio == "1" || selectedRadio == "2") ? "0" : "1";
return false;
}
Changes to do in HTML side
<body style="background-color: #f2f2f2;">
<form action="some.htm" method="post">
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="text" name="criteria" id="hdnSelectedRadValue">
<input type="submit" name="action" value="Go" onclick="setValue();">
</form>
</body>
var radios =
document.querySelectorAll('input[type=radio][name="game"]');
radios.forEach(radio => radio.addEventListener(
'change', () => {
document.getElementsByName("criteria")[0].value =
parseInt(radio.value, 10) > 2 ? '1' : '0';
}
));
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" value="1">
<input type="submit" name="action" value="Go">
You can simply listen to "change" events on all of the radio buttons, then just set the value accordingly.
Here's the snippet code I have written and tested
(function(){
let hdfValue = document.getElementById("myhiddenfield")
let radioButtons = document.querySelectorAll('input[name="game"]');
let submitButton = document.querySelector('input[name="action"]')
radioButtons.forEach((input) => {
input.addEventListener('change', function(e){
let radioButtonValue = e.target.value
if(radioButtonValue == 1 || radioButtonValue == 2){
hdfValue.value = 0;
} else {
hdfValue.value = 1;
}
});
});
submitButton.addEventListener("click", function() {
console.log(hdfValue.value)
});
})()
<form>
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" id="myhiddenfield" value="1">
<input type="button" name="action" value="Go">
</form>

How do I get values when radio button is checked?

I have three radio buttons with another input. What I want is when I click on any radio button those another input value should be display in the label tag. I try some code but It's not correct.
function displayRadioValue() {
var ele = document.getElementsByName('plan');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("investplan").innerHTML = document.getElementById("planinvest").value;
}
}
<input type="radio" name="plan" checked onclick="displayRadioValue()" />
<input type="text"value="10" id="planinvest1" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text"value="20" id="planinvest2" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text"value="30" id="planinvest3" class="hidden-plan-type">
<label id="investplan"></label>
You can use nextElementSibling like in document.getElementById("investplan").innerHTML = ele[i].nextElementSibling.value;
Demo
function displayRadioValue() {
var ele = document.getElementsByName('plan');
for (i = 0; i < ele.length; i++) {
if (ele[i].checked)
document.getElementById("investplan").innerHTML = ele[i].nextElementSibling.value;
}
}
<input type="radio" name="plan" checked onclick="displayRadioValue()" />
<input type="text" value="10" id="planinvest1" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text" value="20" id="planinvest2" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text" value="30" id="planinvest3" class="hidden-plan-type">
<label id="investplan"></label>
you can try this
only if That radio buttons are fixed id's and name
document.getElementById("investplan").innerHTML = "Invest plan is"+document.getElementById("planinvest"+(i+1)).value;
here i am concatenating checkbox index +1 and getting values of planinvestX value.
Full code:
function displayRadioValue() {
var ele = document.getElementsByName('plan');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("investplan").innerHTML = "Invest plan is "+document.getElementById("planinvest"+(i+1)).value;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="radio" name="plan" checked onclick="displayRadioValue()" />
<input type="text" value="10" id="planinvest1" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text" value="20" id="planinvest2" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text" value="30" id="planinvest3" class="hidden-plan-type">
<label id="investplan"></label>
</body>
</html>
Here is a solid way to do it. I've added labels to these element groups because it makes it easier to access the associated text element value, and also because it's good practice in forms.
I set up the event listeners in a script rather than repeat them inline for each element. Again, just good practice and keeps logic separated from content.
I've also added a way to kick it off on page load and populate that element immediately based on whatever default checked value exists.
window.onload = function() {
[...document.querySelectorAll('input[name="plan"]')].forEach(el => el.addEventListener('change', displayRadioValue));
function displayRadioValue(e) {
if (e.target.checked) {
let val = e.target.closest('label').querySelector('input[type="text"]').value;
document.getElementById("investplan").innerHTML = val;
}
}
//initialize
displayRadioValue({
target: document.querySelector('input[name="plan"]:checked')
})
}
label {
display: block;
margin-bottom: 5pc'
}
<label>
<input type="radio" name="plan" checked />
<input type="text" value="10" id="planinvest1" class="hidden-plan-type">
</label>
<label>
<input type="radio" name="plan" />
<input type="text" value="20" id="planinvest2" class="hidden-plan-type">
</label>
<label>
<input type="radio" name="plan" />
<input type="text" value="30" id="planinvest3" class="hidden-plan-type">
</label>
<label id="investplan"></label>
You can get value of input by it's id dynamically
Demo
function displayRadioValue() {
var ele = document.getElementsByName('plan');
for(i = 0; i < ele.length; i++) {
let inputIndex = i+1
if(ele[i].checked)
document.getElementById("investplan").innerHTML = document.getElementById(`planinvest${inputIndex}`).value;
}
}
<input type="radio" name="plan" checked onclick="displayRadioValue()" />
<input type="text"value="10" id="planinvest1" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text"value="20" id="planinvest2" class="hidden-plan-type">
<input type="radio" name="plan" onclick="displayRadioValue()" />
<input type="text"value="30" id="planinvest3" class="hidden-plan-type">
<label id="investplan"></label>

Add Radio button value to summation variable (javascript )

if I have a variable like sum = 20 and I have a numbers of radio buttons with value(number) for each one of them how can I add the value of checked radio button only to sum variable and when check another radio button value will add to sum variable and remove other checked radio value before
You need to add event listeners to the inputs and change the sum accordingly:
let radios = document.getElementsByClassName("numberRadio");
let number = 20;
sum.innerHTML = number;
for(let i = 0; i < radios.length; i++)
radios[i].addEventListener("click", addNumbers);
function addNumbers(event){
let total = number;
for(let i = 0; i < radios.length; i++)
if(radios[i].checked)
total += parseInt(radios[i].value);
sum.innerHTML = total;
}
<input type="radio" class="numberRadio" id="one" name="number" value="1">
<label for="one">1</label><br>
<input type="radio" class="numberRadio" id="two" name="number" value="2">
<label for="two">2</label><br>
<input type="radio" class="numberRadio" id="three" name="number" value="3">
<label for="three">3</label>
<br><br>
<input type="radio" class="numberRadio" id="four" name="number1" value="4">
<label for="four">4</label><br>
<input type="radio" class="numberRadio" id="five" name="number1" value="5">
<label for="five">5</label><br>
<input type="radio" class="numberRadio" id="six" name="number1" value="6">
<label for="six">6</label>
<p id="sum"></p>

How to reset or uncheckvalue of radio button with same name

I am trying to make a MCQ quiz question, where each question carries 4 options. I want to put individual reset button for each questions. When i click on reset button it reset or uncheck all radio button. How to reset radio button of same group or name?
<div class="col-lg-10 col-md-10 col-sm-9">
<div class="lms_service_detail">
<h3>An object is represented by two attributes, out of which one is characteristics and the other one is ___________.</h3>
<p><input name="1" id="Radio1" type="radio" value="A" /> Behaviour</p>
<p><input name="1" id="Radio2" type="radio" value="B" /> Situation</p>
<p><input name="1" id="Radio3" type="radio" value="C" /> Abstraction</p>
<p><input name="1" id="Radio4" type="radio" value="D" /> Encapsulation</p>
<p><input id="Submit1" type="submit" value="Reset" /></p>
</div>
</div>
<div class="col-lg-10 col-md-10 col-sm-9">
<div class="lms_service_detail">
<h3>Name the programming technique that implements programs as an organized collection of interactive objects.</h3>
<p><input name="2" id="Radio5" type="radio" value="A" /> Procedural Programming</p>
<p><input name="2" id="Radio6" type="radio" value="B" /> Modular Programming</p>
<p><input name="2" id="Radio7" type="radio" value="C" /> Object-Oriented Programming</p>
<p><input name="2" id="Radio8" type="radio" value="D" /> None of these</p>
<p><input id="Submit2" type="submit" value="Reset" /></p>
</div>
</div>
function onResetClick() {
var $firstQuestion = document.querySelectorAll('input[name=1]');
var $secondQuestion = document.querySelectorAll('input[name=2]');
for (var i = 0; i < $firstQuestion.length; i++) {
var $el = $firstQuestion;
$el.setAttribute('checked', false);
}
for (i = 0; i < $secondQuestion.length; i++) {
$el = $secondQuestion;
$el.setAttribute('checked', false);
}
}
Binding the onResetClick method will first get all the inputs corresponding to the questions. Then, we iterate over the elements and setAttribute checked as false. No jQuery required.
In JQuery you can use:
$('input[name=Choose]').attr('checked',false); //for a specific radio button
OR
$('input').attr('checked',false); //for all radio buttons
And In JavaScript:
var ele = document.getElementsByName("Choose");
ele.checked = false; //for specific element
OR
var inputs = document.getElementsByTagName('input');
for(var i=0;i<inputs .length;i++)
inputs [i].checked = false; //for all radio buttons

serializing radio buttons

I have a group of radio buttons like this
<input type="radio" name="test" value="h" />
<input type="radio" name="test" value="g" />
<input type="radio" name="test" value="s" />
Now I am serialzing the form to save their values, next time from the saved serialized form values I want load these radio buttons correctly, but its not showing the selected radio button correctly.
I am showing the form's serialized values into the page like this
var obj = $('form').serializeObject();
for(var r in obj){
if(obj.hasOwnProperty(r)){
var nr = obj[r];
$('[name='+r+']').val(nr);
}
}
HTML:
<form id="foo">
<input type="radio" name="test" value="h" />
<input type="radio" name="test" value="g" />
<input type="radio" name="test" value="s" />
<button id="button">foo</button>
</form>
<form id="bar">
<input type="radio" name="test" value="h" />
<input type="radio" name="test" value="g" />
<input type="radio" name="test" value="s" />
</form>
Javascript:
(function() {
$('#button').click(function(e) {
e.preventDefault();
var foo = $('#foo').serializeArray();
for(var i in foo) {
if(foo.hasOwnProperty(i)) {
$('[name="'+foo[i]['name']+'"][value="'+foo[i]['value']+'"]').each(function() {
$(this).attr('checked', true);
})
}
}
})
})();

Categories

Resources