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>
Related
I am trying to create a pricing calculator that takes all of the checked radio buttons and pushes them into an array where it is added in the end. However, I would like to have one of the radio buttons take the attribute of the first radio button and multiply it by its own value.
I tried nesting an if statement inside of another if statement but it will only seem to add the values of the first if statement and ignore the second.
$(".w-radio").change(function() {
var totalPrice = 0,
values = [];
$("input[type=radio]").each(function() {
if ($(this).is(":checked")) {
if ($(this).is('[name="catering"]')) {
var cateringFunc = (
$(this).val() * $('[name="gastronomy"]').attr("add-value")
).toString();
values.push($(this).val());
}
values.push($(this).val());
totalPrice += parseInt($(this).val());
}
});
$("#priceTotal span").text(totalPrice);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="hack43-radio-group w-radio">
<input type="radio" name="gastronomy" value="0" add-value="10">0<BR>
<input type="radio" name="gastronomy" value="550" add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" add-value="10">550<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="venue" value="0">0<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="catering" value="0">0<BR>
<input type="radio" name="catering" value="40">40<BR>
<input type="radio" name="catering" value="45">45<BR>
<input type="radio" name="catering" value="60">60<BR>
</label>
<div class="hack42-45-added-value-row">
<div id="priceTotal">
<span>0</span>
</div>
</div>
When the condition is true you should use cateringFunc instead of $(this).val() when pushing into the values array and adding to totalPrice.
I assume you only want to get the added value from the selected radio button, so I added :checked to the selector. Then you also need to provide a default value if none of the gastronomy buttons are checked.
You shouldn't make up new attributes like add-value. If you need custom attributes, use data-XXX. These can be accessed using the jQuery .data() method.
$(".w-radio").change(function() {
var totalPrice = 0,
values = [];
$("input[type=radio]:checked").each(function() {
if ($(this).is('[name="catering"]')) {
var cateringFunc = (
$(this).val() * ($('[name="gastronomy"]:checked').data("add-value") || 0)
);
values.push(cateringFunc.toString());
totalPrice += cateringFunc;
}
values.push($(this).val());
totalPrice += parseInt($(this).val());
});
$("#priceTotal span").text(totalPrice);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="hack43-radio-group w-radio">
<input type="radio" name="gastronomy" value="0" data-add-value="10">0<BR>
<input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="venue" value="0">0<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="catering" value="0">0<BR>
<input type="radio" name="catering" value="40">40<BR>
<input type="radio" name="catering" value="45">45<BR>
<input type="radio" name="catering" value="60">60<BR>
</label>
<div class="hack42-45-added-value-row">
<div id="priceTotal">
<span>0</span>
</div>
</div>
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>
I currently have a bootstrap tab panel which consists of 3 tabs. Each tab has various number of checkboxes (I do not have control over this they are populated dynamically). What I am trying to achieve is to select the radio button with the id that matches my variable lets say 3. However, if the id does not match I always want to select the last check box.
This is what I have come up with so far.
var defaultSelection = 3;
if (defaultSelection) {
var radioOptions = document.querySelectorAll('[name="firstSet"], [name="secondSet"], [name="thirdSet"]');
for (var i = 0; i < radioOptions.length; i++)
{
if (radioOptions[i].id === defaultSelection)
{
document.querySelector("input[name=" + radioOptions[i].name + "][id=\'" + defaultSelection + "\']").checked = true;
} else {
//not entirly sure how to check the last item here in the particular tab
}
}
}
Markup looks like:
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="firstSet" id="1" value="1"> 1
</label>
<label class="radio-inline btn-sm">
<input type="radio" name="firstSet" id="2" value="2"> 2
</label>
<label class="radio-inline btn-sm radio-active">
<input type="radio" name="firstSet" id="3" value="3"> 3
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="4" value="4"> 4
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="5" value="5"> 5
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="secondSet" id="25" value="25"> 25
</label>
<label class="radio-inline">
<input type="radio" name="secondSet" id="27" value="27"> 27
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="thirdSetSet" id="55" value="55"> 55
</label>
</div>
The above works to check the radio with the id which matches my variable but I'm not entirely sure how to select the last option in a particular tab if none are select or match my variable entry.
Any pointers would be helpful.
One way you could go about this is by keeping track of whether the default radio button has been found and checked, and if that's not the case, then just check the last radio button.
Here's an example that implements this solution:
var defaultSelection = 3;
if (defaultSelection) {
var firstSet = document.querySelectorAll('[name="firstSet"]');
var secondSet = document.querySelectorAll('[name="secondSet"]');
var thirdSet = document.querySelectorAll('[name="thirdSet"]');
var tabs = [].concat(firstSet, secondSet, thirdSet);
tabs.forEach(function(tab) {
// keep track of whether default has been checked and
// grab the last radio button from the tab
var isDefaultChecked = false;
var lastRadioButton = tab[tab.length - 1];
for (var i = 0; i < tab.length; i++) {
var radio = tab[i];
var isDefaultSelection = parseInt(radio.id, 10) === 3;
// check the default radio button and
// set `isDefaultChecked` to true
if (isDefaultSelection) {
radio.checked = true;
isDefaultChecked = true;
}
}
// if no radio button was checked,
// check the last radio button
if (!isDefaultChecked) {
lastRadioButton.checked = true;
}
});
}
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="firstSet" id="1" value="1" /> 1
</label>
<label class="radio-inline btn-sm">
<input type="radio" name="firstSet" id="2" value="2" /> 2
</label>
<label class="radio-inline btn-sm radio-active">
<input type="radio" name="firstSet" id="3" value="3" /> 3
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="4" value="4" /> 4
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="5" value="5" /> 5
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="secondSet" id="25" value="25" /> 25
</label>
<label class="radio-inline">
<input type="radio" name="secondSet" id="27" value="27" /> 27
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="thirdSet" id="55" value="55" /> 55
</label>
</div>
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>
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