How to access the value of this input field that is checked by its name attribute using Javascript :
<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
I write this :
document.querySelector('input[name="rate"]:checked').value;
but there is an error:
TypeError: document.querySelector(...) is null
And I do not want to be checked any inputs by default
Not sure if this will help you, but this snippet lets you select the value of the radio element that is checked, if it exists.
radioElems = document.querySelectorAll("input[name='rate']");
radioElems.forEach((elem) => {
if (elem.checked) {
console.log(`Check found with value ${elem.value}`);
} else {
console.log("Not checked");
}
});
You're missing quotes:
document.querySelector('input[name="rate"]:checked').value;
you should call function for each radio button change event
function handleRadioButtonChange() {
console.log(document.querySelector('input[name="rate"]:checked').value);
}
<input type="radio" class="radioButton" name="rate" value="1" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="2" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="3" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="4" onchange="handleRadioButtonChange()">
You can check if any element matches your querySelector before accessing the value like this:
document.querySelector('input[name="rate"]:checked') && document.querySelector('input[name="rate"]:checked').value
Run a function every time the input change status changes using onchange this function, in turn, logs the value of the clicked input
var rate = document.querySelectorAll(('input[name="rate"]'))
rate.forEach( each => (each.onchange = () => (console.log(each.value))))
<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
What you're doing is absolutely correct! You just need to call this in onchange of the input. Since, you're calling this when no inputs are checked, you're getting this error.
function handleChange1(){
console.log(document.querySelector('input[name="rate"]:checked').value);
}
<input type="radio" onchange="handleChange1();" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
Related
I would like to transfer radio button data from the first html to the second with Pure JavaScript Its ok if you use some jQuery.
jQuery used
1st HTML
<body>
<label for="1">
<input type="radio" name="num" id="1" checked="checked" value="1" >1
</label>
<label for="2">
<input type="radio" name="num" id="2" value="2" >2
</label>
<label for="3" >
<input type="radio" name="num" id="3" value="3" >3
</label>
<label for="4">
<input type="radio" name="num" id="4" value="4" >4
</label>
<button onclick="saveSession()">save</button>
<script type="text/javascript">
function saveSession(){
// I want to save the value of the radio button to sessionStorage here
}
</script>
</body>
In my second HTML I would like to retrieve this data and set the value of the radio buttons to the same.
2nd HTML
<body onload="type()">
<label for="1">
<input type="radio" name="num" id="1" checked="checked" value="1" >1
</label>
<label for="2">
<input type="radio" name="num" id="2" value="2" >2
</label>
<label for="3" >
<input type="radio" name="num" id="3" value="3" >3
</label>
<label for="4">
<input type="radio" name="num" id="4" value="4" >4
</label>
<script type="text/javascript">
function type(){
//I want to get the data with sessionStorage.getItem()
}
</script>
</body>
It would be better if you can also tell me how to disable the form
Thanks in advance for your time and effort!!
Adding my comments as an answer. To access the radio button value, since you're using jQuery, try this:
$('input[name="num"]:checked').val();
On the first HTML page,
sessionStorage.setItem("num", $('input[name="num"]:checked').val());
And then on the second page,
sessionStorage.getItem("num");
or, to set the value of the radio on the 2nd page with the stored value:
$('input[name="num"]').val([sessionStorage.getItem("num")]);
Here is a fiddle: https://jsfiddle.net/8or3chye/
You can add a change event handler to your radios and save a new value to the local storage on that event. Afterwards on page load you need to read the saved value of the radio from the local storage and if it exists - you find an element by id and set checked to true
<label for="1">
<input type="radio" name="num" id="1" value="1" onclick="handleClick(this);" >1
</label>
<label for="2">
<input type="radio" name="num" id="2" value="2" onclick="handleClick(this);" >2
</label>
<label for="3" >
<input type="radio" name="num" id="3" value="3" onclick="handleClick(this);" >3
</label>
<label for="4">
<input type="radio" name="num" id="4" value="4" onclick="handleClick(this);" >4
</label>
<script type="text/javascript">
function handleClick(radio) {
localStorage.setItem('numRadio', radio.value)
}
(function() {
const radioValue = localStorage.getItem('numRadio')
if(radioValue) {
const targetRadio = document.getElementById(radioValue)
targetRadio.checked = true
}
})()
</script>
I have a form/questionnaire where the user must choose various options in HTML.
Javascript will then add up all the options; there are more forms that will be added up to create a grand total.
I know that I need to use parseInt and various if statements:
if option 1 is selected, return value
if option 2 is selected, return value
and so on..
HTML:
<input type="radio" name="age" id= "age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id= "age2" value="5"> 26-40<br>
<input type="radio" name="age" id= "age3" value="8"> 41-60<br>
<input type="radio" name="age" id= "age4" value="10"> 60+<br>
Javascript:
calculateAge () {
var age = parseInt (document.getElementById('age1').value)
if (age = checked) return age;
console.log('age')
}
I assume you want to do a sum over all selected radio button values on click of e.g. a button.
The core of this apporach is to only select those radio buttons which are checked input[type=radio]:checked. If you have those, it's easy to use Array.prototype.reduce to boil that collection down to the sum.
calc.addEventListener('click', sumToVariable)
var sum;
function sumUp() {
let sum = [...document.querySelectorAll('input[type=radio]:checked')]
.reduce(
(acc, val) => acc + Number(val.value)
, 0
)
result.textContent = sum;
return sum;
}
function sumToVariable() {
sum = sumUp();
console.log(sum);
}
body {
font-size: 10px;
}
#result:not(:empty)::before {
content: "Sum of selected options: ";
}
<input type="radio" name="age" id="age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id="age2" value="5"> 26-40<br>
<input type="radio" name="age" id="age3" value="8"> 41-60<br>
<input type="radio" name="age" id="age4" value="10"> 60+<br>
<hr />
<input type="radio" name="age2" id="age10" value="0" checked> 1-25<br>
<input type="radio" name="age2" id="age20" value="5"> 26-40<br>
<input type="radio" name="age2" id="age30" value="8"> 41-60<br>
<input type="radio" name="age2" id="age40" value="10"> 60+<br>
<hr />
<button type="button" id="calc">Calc</button>
<div id="result"></div>
You could as well do the same on change of a radio button:
radiobuttons.addEventListener('change', () => {
result.textContent = [...document.querySelectorAll('input[type=radio]:checked')]
.reduce(
(acc, val) => acc + Number(val.value)
, 0
)
}
)
body {
font-size: 10px;
}
#result:not(:empty)::before {
content: "Sum of selected options: ";
}
<div id="radiobuttons">
<input type="radio" name="age" id="age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id="age2" value="5"> 26-40<br>
<input type="radio" name="age" id="age3" value="8"> 41-60<br>
<input type="radio" name="age" id="age4" value="10"> 60+<br>
<hr />
<input type="radio" name="age2" id="age10" value="0" checked> 1-25<br>
<input type="radio" name="age2" id="age20" value="5"> 26-40<br>
<input type="radio" name="age2" id="age30" value="8"> 41-60<br>
<input type="radio" name="age2" id="age40" value="10"> 60+<br>
</div>
<hr />
<div id="result"></div>
age = checked
cannot work, because age is an int, and a single equal sign is not used for comparison. Also checked is a property and not a comparable. You could use it like so:
function calculateAge () {
let age = parseInt (document.getElementById('age1').value)
if (document.getElementById('age1').checked) return age;
console.log('age')
}
Also you didnt ask a question, assuming you want to know why there is nothing returned.
I have the below html code
<fieldset id="a">
<input type="radio" name="choice1" value="1" radioatrr="0" class="myvalue1" /><label for="choice1">text 1</label>
<input type="radio" name="choice2" value="2" radioatrr="0" class="myvalue2" /><label for="choice2">text 2</label>
<input type="radio" name="choice3" value="3" radioatrr="0" class="myvalue3" /><label for="choice3">text 3</label>
</fieldset>
<fieldset id="b">
<input type="radio" name="cb-choice1" value="4" radioatrr="1" class="myvalue4" /><label for="cb-choice1">text 4</label>
<input type="radio" name="cb-choice2" value="5" radioatrr="1" class="myvalue5" /><label for="cb-choice2">text 5</label>
</fieldset>
I want if choice2 is checked and one of cb-choice1 or cb-choice2 then the received value is the value of cb-... choice (4 or 5) if choice2 is checked and no cb-... is checked then the received value is 2.
How can I do this?
I try this
$("input:checked").each(function(i) {
if (($(this).attr("radioatrr") == 0)) {
alert(($(this).attr("value"));
}
})
but can not working as I want
You can check out this tutorial from W3 to help you out:
https://www.w3schools.com/jsref/prop_radio_value.asp
In regards to your problem, you can hook in this function:
function handleRadioSelection() {
if(document.getElementByName('choice2').checked) {
if (document.getElementByName('cb-choice1').checked) {
return document.getElementByName('cb-choice1').value
} else if (document.getElementByName('cb-choice2').checked) {
return document.getElementByName('cb-choice2').value
} else {
return document.getElementByName('choice2').value
}
}
}
I'm using a hidden input field to capture the value that you want, you can change it to anything else. I've also modified the radio buttons into two groups, as from reading the question/requirements I think that's how it should be setup.
$("#submit").click(function() {
//capture group 1 and group 2 value that's checked
var val1 = $('input[name=choice]:checked').val();
var val2 = $('input[name=choice2]:checked').val();
//capture the input object with the desired value
var sendVal = $('input[name=myval]');
//reset value to 0 as this happens on click, incase value gets changed
sendVal.val(0);
//if group 1 is 2 and there is a value selected in group2
if(val1==2&&val2 != undefined){
sendVal.val(val2);
//if group 1 is 2 and group 2 is not selected
}else if(val1==2&&val2 == undefined){
sendVal.val(val1);
}
//showing value to be sent in an alert
alert(sendVal.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Group 1</h2>
<input type="radio" name="choice" value="1" class="myvalue1" /><label for="choice1">text 1</label>
<input type="radio" name="choice" value="2" class="myvalue2" /><label for="choice2">text 2</label>
<input type="radio" name="choice" value="3" class="myvalue3" /><label for="choice3">text 3</label>
<h2>Group 2</h2>
<input type="radio" name="choice2" value="4" class="myvalue4" /><label for="cb-choice1">text 4</label>
<input type="radio" name="choice2" value="5" class="myvalue5" /><label for="cb-choice2">text 5</label>
<input type="hidden"name="myval" value="0">
<br/>
<button id="submit">submit</button>
There are two radio buttons in my code:
<input type="radio" id='production' ng-click="division($event)" ng-model="formData.division" value="Production">
<label for="production">Production</label>
<input type="radio" id='operation' ng-click="division($event)" ng-model="formData.division" value="Operations">
<label for="operation">Operations</label>
And there are more radio buttons after:
<div class="prod">
<h2>Production</h2>
<label><b>Project Captain: <small id="small">*</small></b></label>
<input type="radio" class="projCap" ng-model="formData.projCap" value="yes">Yes
<input type="radio" class="projCap" ng-model="formData.projCap" value="no">No
<label><b>Supervisor: <small id="small">*</small></b></label>
<input type="radio" ng-model="formData.supervisor" value="yes">Yes
<input type="radio" ng-model="formData.supervisor" value="no">No<br><br>
</div>
<div class="op">
<h2>Operations</h2>
<label><b>Manager: <small id="small">*</small></b></label>
<input type="radio" ng-model="formData.mngr" value="yes">Yes
<input type="radio" ng-model="formData.mngr" value="no">No
<label><b>Assistant Manager: <small id="small">*</small></b></label>
<input type="radio" ng-model="formData.asMngr" value="yes">Yes
<input type="radio" ng-model="formData.asMngr" value="no">No <br><br>
</div>
I want to save time for the user so for example if user selects Production it should automatically set all radio buttons to no inside div op.
If Operations all radio buttons with value no should be selected inside div prod.
My function in controller:
$scope.division = function(event) {
if(event.target.id === 'production'){
$('.op').find('input:radio').prop('checked', true);
$('.prod').find('input:radio').prop('checked', false);
}else{
$('.prod').find('input:radio').prop('checked', true);
$('.op').find('input:radio').prop('checked', false);
}
};
It will select both yes and no values:
How can I auto select only radio buttons with no value?
Try this:
$('.op').find('input:radio[value="no"]').prop('checked', true);
and don't forget to provide the same name to all radio that comes under a group, otherwise they work as checkboxes.
Check this example:
$(document).ready(function(){
$('.op').find('input:radio[value="no"]').prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="op">
<h2>Operations</h2>
<label><b>Manager: <small id="small">*</small></b></label>
<input type="radio" name="group1" ng-model="formData.mngr" value="yes">Yes
<input type="radio" name="group1" ng-model="formData.mngr" value="no">No
<label><b>Assistant Manager: <small id="small">*</small></b></label>
<input type="radio" name="group2" ng-model="formData.asMngr" value="yes">Yes
<input type="radio" name="group2" ng-model="formData.asMngr" value="no">No <br><br>
</div>
I have a form in which i have two sets of radio buttons and one textbox to enter the quantity value.
Based on the radio button selected and value in quantity textbox the total textbox should get populated with values.
I am using array to do the calculation but the value in total fields is displayed as NAN.
Can anyone check my code and let me know where i am wrong??
**HTML**
<form id="orderform" name="orderform" >
<fieldset data-role="controlgroup">
<legend><b>Choice</b></legend>
<input type="radio" name="choice" id="veg" value="1" checked onclick="total()">
<label for="veg">Vegetarian</label>
<input type="radio" name="choice" id="nonveg" value="2" onclick="total()">
<label for="nonveg">Meat Lover</label>
</fieldset>
<fieldset data-role="controlgroup">
<legend><b>Size</b></legend>
<input type="radio" name="size" id="small" onclick="total()">
<label for="small">Small</label>
<input type="radio" name="size" id="medium" onclick="total()">
<label for="medium">Medium</label>
<input type="radio" name="size" id="large" onclick="total()">
<label for="large">Large</label><span class="validation"></span>
</fieldset>
<div><b>Quantity</b>
<input type="text" id ="qty" name="qty" size="5" onclick="total()">
</div><div>
<b>Total</b>
<input type="text" id="amt" name="amt" readonly="readonly">
</div>
Javascript
Javascript
var array=[[8.99,9.99,10.99],[9.99,10.99,11.99]];
function total()
{
var row = document.querySelector('input[name="choice"]:checked').value;
var column = document.querySelector('input[name="size"]:checked').value;
var qty=document.getElementById("qty").value;
var total=0;
total= (array[row][column]+1)*qty;
document.orderform.amt.value = total;
}
You have to change size group in html like below
<legend><b>Size</b></legend>
<input type="radio" name="size" id="small" value="1" onclick="total()">
<label for="small">Small</label>
<input type="radio" name="size" id="medium" value="2" onclick="total()">
<label for="medium">Medium</label>
<input type="radio" name="size" id="large" value="3" onclick="total()">
<label for="large">Large</label><span class="validation"></span>
it will work for you
var column = document.querySelector('input[name="size"]:checked').value;
you can alert(column), you'll find that value is "on". because you didn't setup any value in all of your size group