Use another attribute instead of the input value to update total - javascript

basically the below code creates a order total in the id="total" span depending on which checkbox/radio buttons are selected. The total is changed by the value of the checkbox/radio buttons however i was wondering if there's any other way to change the total without using the inputs value because its needed in the next part of the form. Maybe another input attribute? I'm just not sure how to go about it.
All help will be greatly appreciated, thank you!
<form action="cart.php" method="post" name="builder">
<input checked="checked" type="radio" name="term" value="12" onclick='check_value(this, 1)' />
<input type="radio" name="term" value="24" onclick='check_value(this, 2)' />
<input type="radio" name="term" value="36" onclick='check_value(this, 3)' />
<input type="checkbox" name="cid[]" value="2" onclick='check_value(this, "")' />
<input type="checkbox" name="cid[]" value="3" onclick='check_value(this, "")' />
<input type="checkbox" name="cid[]" value="4" onclick='check_value(this, "")' />
Total Order: $<span id="total">36</span>
</form>
function check_value(curElem, id) {
// calculate Total
var total = 0;
var controls = document.getElementsByTagName('input');
for (var i = 0; i < controls.length; i++) {
if ((controls[i].type === 'radio' || controls[i].type === 'checkbox') && controls[i].checked) {
total = total + parseFloat(controls[i].value);
}
}
document.getElementById("total").innerHTML = total;
//alert("Total: " + total);
}

if you really want to use another attribute, use it
use an attribute of your choice, say nval and access it as controls[i].getAttribute("nval")
otherwise,
you can create plenty of hidden input fields in the page, for each checkbox to hold your value. and use these hidden fields to compute total.

Related

how to retrieve the value of a radio button [duplicate]

I want to get the selected value from a group of radio buttons.
Here's my HTML:
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
Here's my js:
var rates = document.getElementById('rates').value;
var rate_value;
if(rates =='Fixed Rate'){
rate_value = document.getElementById('r1').value;
}else if(rates =='Variable Rate'){
rate_value = document.getElementById('r2').value;
}else if(rates =='Multi Rate'){
rate_value = document.getElementById('r3').value;
}
document.getElementById('results').innerHTML = rate_value;
I keep getting undefined.
This works in IE9 and above and all other browsers.
document.querySelector('input[name="rate"]:checked').value;
var rates = document.getElementById('rates').value;
The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.
The checked property will tell you whether the element is selected:
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
Or
$("input[type='radio'][name='rate']:checked").val();
You can get the value by using the checked property.
var rates = document.getElementsByName('rate');
var rate_value;
for(var i = 0; i < rates.length; i++){
if(rates[i].checked){
rate_value = rates[i].value;
}
}
For you people living on the edge:
There is now something called a RadioNodeList and accessing it's value property will return the value of the currently checked input. This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.
Example Form
<form id="test">
<label><input type="radio" name="test" value="A"> A</label>
<label><input type="radio" name="test" value="B" checked> B</label>
<label><input type="radio" name="test" value="C"> C</label>
</form>
To retrieve the checked value, you could do something like this:
var form = document.getElementById("test");
alert(form.elements["test"].value);
The JSFiddle to prove it: http://jsfiddle.net/vjop5xtq/
Please note this was implemented in Firefox 33 (All other major browser seems to support it). Older browsers will require a polfyill for RadioNodeList for this to properly function
If you are using javascript without jQuery, you can use this command :
document.querySelector("input[type='radio'][name=rate]:checked").value;
The one worked for me is given below from api.jquery.com.
HTML
<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>
JavaScript
var selectedOption = $("input:radio[name=option]:checked").val()
The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2
Another (apparently older) option is to use the format:
"document.nameOfTheForm.nameOfTheInput.value;"
e.g. document.mainForm.rads.value;
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
result.innerHTML = 'You selected: '+radVal;
}
<form id="mainForm" name="mainForm">
<input type="radio" name="rads" value="1" />
<input type="radio" name="rads" value="2" />
<input type="radio" name="rads" value="3" />
<input type="radio" name="rads" value="4" />
</form>
<span id="result"></span>
You can refer to the element by its name within a form. Your original HTML does not contain a form element though.
Fiddle here (works in Chrome and Firefox):
https://jsfiddle.net/Josh_Shields/23kg3tf4/1/
Use document.querySelector('input[type = radio]:checked').value; to get value of selected checkbox , you can use other attributes to get value like name = gender etc. please go through below snippet definitely it will helpful to you,
Solution
document.mainForm.onclick = function(){
var gender = document.querySelector('input[name = gender]:checked').value;
result.innerHTML = 'You Gender: '+gender;
}
<form id="mainForm" name="mainForm">
<input type="radio" name="gender" value="Male" checked/>Male
<input type="radio" name="gender" value="Female" />Female
<input type="radio" name="gender" value="Others" />Others
</form>
<span id="result"></span>
Thank-You
HTML CODE:
<input type="radio" name="rdoName" value="YES"/>
<input type="radio" name="rdoName" value="NO"/>
JQUERY CODE:
var value= $("input:radio[name=rdoName]:checked").val();
$("#btnSubmit").click(function(){
var value=$("input:radio[name=rdoName]:checked").val();
console.log(value);
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="rdoName" value="YES"/> YES
<input type="radio" name="rdoName" value="NO"/> NO
<br/>
<input type="button"id="btnSubmit"value="Which one Selected"/>
You will get
value="YES" //if checked Radio Button with the value "YES"
value="NO" //if checked Radio Button with the value "NO"
Shortest
[...rates.children].find(c=>c.checked).value
let v= [...rates.children].find(c=>c.checked).value
console.log(v);
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
In Javascript we can get the values by using Id's "getElementById()" in the above code you posted has contain name not Id
so you to modify like this
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
use this rate_value according to your code
A year or so has passed since the question was asked, but I thought a substantial improvement of the answers was possible. I find this the easiest and most versatile script, because it checks whether a button has been checked, and if so, what its value is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check radio checked and its value</title>
</head>
<body>
<form name="theFormName">
<input type="radio" name="theRadioGroupName" value="10">
<input type="radio" name="theRadioGroupName" value="20">
<input type="radio" name="theRadioGroupName" value="30">
<input type="radio" name="theRadioGroupName" value="40">
<input type="button" value="Check" onclick="getRadioValue('theRadioGroupName')">
</form>
<script>
function getRadioValue(groupName) {
var radios = theFormName.elements[groupName];
window.rdValue; // declares the global variable 'rdValue'
for (var i=0; i<radios.length; i++) {
var someRadio = radios[i];
if (someRadio.checked) {
rdValue = someRadio.value;
break;
}
else rdValue = 'noRadioChecked';
}
if (rdValue == '10') {
alert('10'); // or: console.log('10')
}
else if (rdValue == 'noRadioChecked') {
alert('no radio checked');
}
}
</script>
</body>
</html>
You can also call the function within another function, like this:
function doSomething() {
getRadioValue('theRadioGroupName');
if (rdValue == '10') {
// do something
}
else if (rdValue == 'noRadioChecked') {
// do something else
}
}
Assuming your form element is referred to by myForm variable below, and that your radio buttons share the name "my-radio-button-group-name", the following is pure JavaScript and standards compliant (although I have not checked it to be available everywhere):
myForm.elements.namedItem("my-radio-button-group-name").value
The above will yield the value of a checked (or selected, as it is also called) radio button element, if any, or null otherwise. The crux of the solution is the namedItem function which works with radio buttons specifically.
See HTMLFormElement.elements, HTMLFormControlsCollection.namedItem and especially RadioNodeList.value, as namedItem usually returns a RadioNodeList object.
(I use MDN because it allows one to track standards compliance, at least to a large degree, and because it is easier to comprehend than many WhatWG and W3C publications)
directly calling a radio button many times gives you the value of the FIRST button, not the CHECKED button. instead of looping thru radio buttons to see which one is checked, i prefer to call an onclick javascript function that sets a variable that can later be retrieved at will.
<input type="radio" onclick="handleClick(this)" name="reportContent" id="reportContent" value="/reportFleet.php" >
which calls:
var currentValue = 0;
function handleClick(myRadio) {
currentValue = myRadio.value;
document.getElementById("buttonSubmit").disabled = false;
}
additional advantage being that i can treat data and/or react to the checking of a button (in this case, enabling SUBMIT button).
You can also loop through the buttons with a forEach-loop on the elements
var elements = document.getElementsByName('radioButton');
var checkedButton;
console.log(elements);
elements.forEach(e => {
if (e.checked) {
//if radio button is checked, set sort style
checkedButton = e.value;
}
});
An improvement to the previous suggested functions:
function getRadioValue(groupName) {
var _result;
try {
var o_radio_group = document.getElementsByName(groupName);
for (var a = 0; a < o_radio_group.length; a++) {
if (o_radio_group[a].checked) {
_result = o_radio_group[a].value;
break;
}
}
} catch (e) { }
return _result;
}
My take on this problem with pure javascript is to find the checked node, find its value and pop it out from the array.
var Anodes = document.getElementsByName('A'),
AValue = Array.from(Anodes)
.filter(node => node.checked)
.map(node => node.value)
.pop();
console.log(AValue);
Note that I'm using arrow functions.
See this fiddle for a working example.
You can use .find() to select checked element:
var radio = Array.from(document.querySelectorAll('#rate input'))
var value = radio.length && radio.find(r => r.checked).value
Here is a solution putting the radio buttons in a constant and getting the selected value only when needed.
const rates = document.forms.rates.elements["rate"]
showRate()
function showRate(){
document.getElementById('results').innerHTML = rates.value
}
<form id="rates" onchange="showRate()">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</form>
<div id="results"></div>
If you are using jQuery:
$('input[name="rate"]:checked').val();
<form id="rates">
<input type="radio" name="rate" value="Fixed Rate"> Fixed
<input type="radio" name="rate" value="Variable Rate"> Variable
<input type="radio" name="rate" value="Multi Rate" checked> Multi
</form>
then...
var rate_value = rates.rate.value;
check value by ID:
var CheckedValues = ($("#r1").is(':checked')) ? 1 : 0;
I used the jQuery.click function to get the desired output:
$('input[name=rate]').click(function(){
console.log('Hey you clicked this: ' + this.value);
if(this.value == 'Fixed Rate'){
rate_value = $('#r1').value;
} else if(this.value =='Variable Rate'){
rate_value = $('#r2').value;
} else if(this.value =='Multi Rate'){
rate_value = $('#r3').value;
}
$('#results').innerHTML = rate_value;
});
Hope it helps.
If the buttons are in a form
var myform = new FormData(getformbywhatever);
myform.get("rate");
QuerySelector above is a better solution. However, this method is easy to understand, especially if you don't have a clue about CSS. Plus, input fields are quite likely to be in a form anyway.
Didn't check, there are other similar solutions, sorry for the repetition
var rates = document.getElementById('rates').value;
cannot get values of a radio button like that instead use
rate_value = document.getElementById('r1').value;
If you are using the JQuery, please use the bellow snippet for group of radio buttons.
var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();
Simply use: document.querySelector('input[rate][checked]').value
https://codepen.io/anon/pen/YQxbZJ
The HTML
<div id="rates">
<input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="x2" name="rate" value="Variable Rate"
checked="checked"> Variable Rate
<input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>
<button id="rdio"> Check Radio </button>
<div id="check">
</div>
The JS
var x ,y;
var x = document.getElementById("check");
function boom()
{
if (document.getElementById("x1").checked)
y = document.getElementById("x1").value;
else if(document.getElementById("x2").checked)
y = document.getElementById("x2").value;
else if (document.getElementById("x3").checked)
y = document.getElementById("x3").value;
else
y = "kuch nhi;"
x.innerHTML = y;
}
var z = document.getElementById('rdio');
z.addEventListener("click", boom);`
var rates=document.getElementsByName("rate");
for (i = 0; i < rates.length; i++) {
if (rates[i].checked) {
console.log(rates[i].value);
rate=rates[i].value;
document.getElementById("rate").innerHTML = rate;
alert(rate);
}
}
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
</br>
<div id='rate'>
</div>
In php it's very easy
html page
Male<input type="radio" name="radio" value="male"><br/>
Female<input type="radio" name="radio" value="female"><br/>
Others<input type="radio" name="radio" value="other"><br/>
<input type="submit" value="submit">
Take value from form to php
$radio=$_POST['radio'];<br/>
use php if(isset($_POST['submit']))<br/>
{<br/>
echo "you selected".$radio."thank u";<br/>
}

How do i link radio image button value to id to send value to the database [duplicate]

I want to get the selected value from a group of radio buttons.
Here's my HTML:
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
Here's my js:
var rates = document.getElementById('rates').value;
var rate_value;
if(rates =='Fixed Rate'){
rate_value = document.getElementById('r1').value;
}else if(rates =='Variable Rate'){
rate_value = document.getElementById('r2').value;
}else if(rates =='Multi Rate'){
rate_value = document.getElementById('r3').value;
}
document.getElementById('results').innerHTML = rate_value;
I keep getting undefined.
This works in IE9 and above and all other browsers.
document.querySelector('input[name="rate"]:checked').value;
var rates = document.getElementById('rates').value;
The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.
The checked property will tell you whether the element is selected:
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
Or
$("input[type='radio'][name='rate']:checked").val();
You can get the value by using the checked property.
var rates = document.getElementsByName('rate');
var rate_value;
for(var i = 0; i < rates.length; i++){
if(rates[i].checked){
rate_value = rates[i].value;
}
}
For you people living on the edge:
There is now something called a RadioNodeList and accessing it's value property will return the value of the currently checked input. This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.
Example Form
<form id="test">
<label><input type="radio" name="test" value="A"> A</label>
<label><input type="radio" name="test" value="B" checked> B</label>
<label><input type="radio" name="test" value="C"> C</label>
</form>
To retrieve the checked value, you could do something like this:
var form = document.getElementById("test");
alert(form.elements["test"].value);
The JSFiddle to prove it: http://jsfiddle.net/vjop5xtq/
Please note this was implemented in Firefox 33 (All other major browser seems to support it). Older browsers will require a polfyill for RadioNodeList for this to properly function
If you are using javascript without jQuery, you can use this command :
document.querySelector("input[type='radio'][name=rate]:checked").value;
The one worked for me is given below from api.jquery.com.
HTML
<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>
JavaScript
var selectedOption = $("input:radio[name=option]:checked").val()
The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2
Another (apparently older) option is to use the format:
"document.nameOfTheForm.nameOfTheInput.value;"
e.g. document.mainForm.rads.value;
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
result.innerHTML = 'You selected: '+radVal;
}
<form id="mainForm" name="mainForm">
<input type="radio" name="rads" value="1" />
<input type="radio" name="rads" value="2" />
<input type="radio" name="rads" value="3" />
<input type="radio" name="rads" value="4" />
</form>
<span id="result"></span>
You can refer to the element by its name within a form. Your original HTML does not contain a form element though.
Fiddle here (works in Chrome and Firefox):
https://jsfiddle.net/Josh_Shields/23kg3tf4/1/
Use document.querySelector('input[type = radio]:checked').value; to get value of selected checkbox , you can use other attributes to get value like name = gender etc. please go through below snippet definitely it will helpful to you,
Solution
document.mainForm.onclick = function(){
var gender = document.querySelector('input[name = gender]:checked').value;
result.innerHTML = 'You Gender: '+gender;
}
<form id="mainForm" name="mainForm">
<input type="radio" name="gender" value="Male" checked/>Male
<input type="radio" name="gender" value="Female" />Female
<input type="radio" name="gender" value="Others" />Others
</form>
<span id="result"></span>
Thank-You
HTML CODE:
<input type="radio" name="rdoName" value="YES"/>
<input type="radio" name="rdoName" value="NO"/>
JQUERY CODE:
var value= $("input:radio[name=rdoName]:checked").val();
$("#btnSubmit").click(function(){
var value=$("input:radio[name=rdoName]:checked").val();
console.log(value);
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="rdoName" value="YES"/> YES
<input type="radio" name="rdoName" value="NO"/> NO
<br/>
<input type="button"id="btnSubmit"value="Which one Selected"/>
You will get
value="YES" //if checked Radio Button with the value "YES"
value="NO" //if checked Radio Button with the value "NO"
Shortest
[...rates.children].find(c=>c.checked).value
let v= [...rates.children].find(c=>c.checked).value
console.log(v);
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
In Javascript we can get the values by using Id's "getElementById()" in the above code you posted has contain name not Id
so you to modify like this
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
use this rate_value according to your code
A year or so has passed since the question was asked, but I thought a substantial improvement of the answers was possible. I find this the easiest and most versatile script, because it checks whether a button has been checked, and if so, what its value is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check radio checked and its value</title>
</head>
<body>
<form name="theFormName">
<input type="radio" name="theRadioGroupName" value="10">
<input type="radio" name="theRadioGroupName" value="20">
<input type="radio" name="theRadioGroupName" value="30">
<input type="radio" name="theRadioGroupName" value="40">
<input type="button" value="Check" onclick="getRadioValue('theRadioGroupName')">
</form>
<script>
function getRadioValue(groupName) {
var radios = theFormName.elements[groupName];
window.rdValue; // declares the global variable 'rdValue'
for (var i=0; i<radios.length; i++) {
var someRadio = radios[i];
if (someRadio.checked) {
rdValue = someRadio.value;
break;
}
else rdValue = 'noRadioChecked';
}
if (rdValue == '10') {
alert('10'); // or: console.log('10')
}
else if (rdValue == 'noRadioChecked') {
alert('no radio checked');
}
}
</script>
</body>
</html>
You can also call the function within another function, like this:
function doSomething() {
getRadioValue('theRadioGroupName');
if (rdValue == '10') {
// do something
}
else if (rdValue == 'noRadioChecked') {
// do something else
}
}
Assuming your form element is referred to by myForm variable below, and that your radio buttons share the name "my-radio-button-group-name", the following is pure JavaScript and standards compliant (although I have not checked it to be available everywhere):
myForm.elements.namedItem("my-radio-button-group-name").value
The above will yield the value of a checked (or selected, as it is also called) radio button element, if any, or null otherwise. The crux of the solution is the namedItem function which works with radio buttons specifically.
See HTMLFormElement.elements, HTMLFormControlsCollection.namedItem and especially RadioNodeList.value, as namedItem usually returns a RadioNodeList object.
(I use MDN because it allows one to track standards compliance, at least to a large degree, and because it is easier to comprehend than many WhatWG and W3C publications)
directly calling a radio button many times gives you the value of the FIRST button, not the CHECKED button. instead of looping thru radio buttons to see which one is checked, i prefer to call an onclick javascript function that sets a variable that can later be retrieved at will.
<input type="radio" onclick="handleClick(this)" name="reportContent" id="reportContent" value="/reportFleet.php" >
which calls:
var currentValue = 0;
function handleClick(myRadio) {
currentValue = myRadio.value;
document.getElementById("buttonSubmit").disabled = false;
}
additional advantage being that i can treat data and/or react to the checking of a button (in this case, enabling SUBMIT button).
You can also loop through the buttons with a forEach-loop on the elements
var elements = document.getElementsByName('radioButton');
var checkedButton;
console.log(elements);
elements.forEach(e => {
if (e.checked) {
//if radio button is checked, set sort style
checkedButton = e.value;
}
});
An improvement to the previous suggested functions:
function getRadioValue(groupName) {
var _result;
try {
var o_radio_group = document.getElementsByName(groupName);
for (var a = 0; a < o_radio_group.length; a++) {
if (o_radio_group[a].checked) {
_result = o_radio_group[a].value;
break;
}
}
} catch (e) { }
return _result;
}
My take on this problem with pure javascript is to find the checked node, find its value and pop it out from the array.
var Anodes = document.getElementsByName('A'),
AValue = Array.from(Anodes)
.filter(node => node.checked)
.map(node => node.value)
.pop();
console.log(AValue);
Note that I'm using arrow functions.
See this fiddle for a working example.
You can use .find() to select checked element:
var radio = Array.from(document.querySelectorAll('#rate input'))
var value = radio.length && radio.find(r => r.checked).value
Here is a solution putting the radio buttons in a constant and getting the selected value only when needed.
const rates = document.forms.rates.elements["rate"]
showRate()
function showRate(){
document.getElementById('results').innerHTML = rates.value
}
<form id="rates" onchange="showRate()">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</form>
<div id="results"></div>
If you are using jQuery:
$('input[name="rate"]:checked').val();
<form id="rates">
<input type="radio" name="rate" value="Fixed Rate"> Fixed
<input type="radio" name="rate" value="Variable Rate"> Variable
<input type="radio" name="rate" value="Multi Rate" checked> Multi
</form>
then...
var rate_value = rates.rate.value;
check value by ID:
var CheckedValues = ($("#r1").is(':checked')) ? 1 : 0;
I used the jQuery.click function to get the desired output:
$('input[name=rate]').click(function(){
console.log('Hey you clicked this: ' + this.value);
if(this.value == 'Fixed Rate'){
rate_value = $('#r1').value;
} else if(this.value =='Variable Rate'){
rate_value = $('#r2').value;
} else if(this.value =='Multi Rate'){
rate_value = $('#r3').value;
}
$('#results').innerHTML = rate_value;
});
Hope it helps.
If the buttons are in a form
var myform = new FormData(getformbywhatever);
myform.get("rate");
QuerySelector above is a better solution. However, this method is easy to understand, especially if you don't have a clue about CSS. Plus, input fields are quite likely to be in a form anyway.
Didn't check, there are other similar solutions, sorry for the repetition
var rates = document.getElementById('rates').value;
cannot get values of a radio button like that instead use
rate_value = document.getElementById('r1').value;
If you are using the JQuery, please use the bellow snippet for group of radio buttons.
var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();
Simply use: document.querySelector('input[rate][checked]').value
https://codepen.io/anon/pen/YQxbZJ
The HTML
<div id="rates">
<input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="x2" name="rate" value="Variable Rate"
checked="checked"> Variable Rate
<input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>
<button id="rdio"> Check Radio </button>
<div id="check">
</div>
The JS
var x ,y;
var x = document.getElementById("check");
function boom()
{
if (document.getElementById("x1").checked)
y = document.getElementById("x1").value;
else if(document.getElementById("x2").checked)
y = document.getElementById("x2").value;
else if (document.getElementById("x3").checked)
y = document.getElementById("x3").value;
else
y = "kuch nhi;"
x.innerHTML = y;
}
var z = document.getElementById('rdio');
z.addEventListener("click", boom);`
var rates=document.getElementsByName("rate");
for (i = 0; i < rates.length; i++) {
if (rates[i].checked) {
console.log(rates[i].value);
rate=rates[i].value;
document.getElementById("rate").innerHTML = rate;
alert(rate);
}
}
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
</br>
<div id='rate'>
</div>
In php it's very easy
html page
Male<input type="radio" name="radio" value="male"><br/>
Female<input type="radio" name="radio" value="female"><br/>
Others<input type="radio" name="radio" value="other"><br/>
<input type="submit" value="submit">
Take value from form to php
$radio=$_POST['radio'];<br/>
use php if(isset($_POST['submit']))<br/>
{<br/>
echo "you selected".$radio."thank u";<br/>
}

jQuery & JavaScript Excercise: Adding Values On Condition

How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO

check all other radio button using one radio button

i am fetching roll numbers here which have two radio buttons in 'php'.there will be multiple number of roll numbers so i want to check all the radio buttons whose value are 'yes' at once using a particular radio button or check box.although i didn't write that button in this code as i don't know what to write.please give me a solution using java script.
while($row=mysqli_fetch_assoc($result))
{
echo"<tr><td>{$row['roll']}</td>
</td><td></td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='Yes'>YES</td>
</td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='No'>NO</td></tr>";
$i++;
}
This type of interaction should be using a Javascript implementation since it is a client-side operation.
HTML:
<form>
<input type="radio" name="radio1" value="yes"/>Yes
<input type="radio" name="radio1" value="no"/>No
<br />
<input type="radio" name="radio2" value="yes"/>Yes
<input type="radio" name="radio2" value="no"/>No
<br />
<input type="radio" name="radio3" value="yes"/>Yes
<input type="radio" name="radio3" value="no"/>No
<br />
<input type="button" value="Select All" onclick="selectAll('radio',true);"/>
<input type="button" value="Deselect All" onclick="selectAll('radio',false);"/>
</form>
Javascript:
function selectAll( prefix, set ) {
var form = document.forms[0], //Get the appropriate form
i = 0,
radio;
while( radio = form[prefix + ++i] ) //Loop through all named radio# elements
for( var j = 0; j < radio.length; j++ ) //Loop through each set of named radio buttons
if( radio[j].value == (set ? "yes" : "no") ) //Selector based on value of set
radio[j].checked = true; //Check that radio button!
}
JSFiddle

How to get value of selected radio button?

I want to get the selected value from a group of radio buttons.
Here's my HTML:
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
Here's my js:
var rates = document.getElementById('rates').value;
var rate_value;
if(rates =='Fixed Rate'){
rate_value = document.getElementById('r1').value;
}else if(rates =='Variable Rate'){
rate_value = document.getElementById('r2').value;
}else if(rates =='Multi Rate'){
rate_value = document.getElementById('r3').value;
}
document.getElementById('results').innerHTML = rate_value;
I keep getting undefined.
This works in IE9 and above and all other browsers.
document.querySelector('input[name="rate"]:checked').value;
var rates = document.getElementById('rates').value;
The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.
The checked property will tell you whether the element is selected:
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
Or
$("input[type='radio'][name='rate']:checked").val();
You can get the value by using the checked property.
var rates = document.getElementsByName('rate');
var rate_value;
for(var i = 0; i < rates.length; i++){
if(rates[i].checked){
rate_value = rates[i].value;
}
}
For you people living on the edge:
There is now something called a RadioNodeList and accessing it's value property will return the value of the currently checked input. This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.
Example Form
<form id="test">
<label><input type="radio" name="test" value="A"> A</label>
<label><input type="radio" name="test" value="B" checked> B</label>
<label><input type="radio" name="test" value="C"> C</label>
</form>
To retrieve the checked value, you could do something like this:
var form = document.getElementById("test");
alert(form.elements["test"].value);
The JSFiddle to prove it: http://jsfiddle.net/vjop5xtq/
Please note this was implemented in Firefox 33 (All other major browser seems to support it). Older browsers will require a polfyill for RadioNodeList for this to properly function
If you are using javascript without jQuery, you can use this command :
document.querySelector("input[type='radio'][name=rate]:checked").value;
The one worked for me is given below from api.jquery.com.
HTML
<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>
JavaScript
var selectedOption = $("input:radio[name=option]:checked").val()
The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2
Another (apparently older) option is to use the format:
"document.nameOfTheForm.nameOfTheInput.value;"
e.g. document.mainForm.rads.value;
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
result.innerHTML = 'You selected: '+radVal;
}
<form id="mainForm" name="mainForm">
<input type="radio" name="rads" value="1" />
<input type="radio" name="rads" value="2" />
<input type="radio" name="rads" value="3" />
<input type="radio" name="rads" value="4" />
</form>
<span id="result"></span>
You can refer to the element by its name within a form. Your original HTML does not contain a form element though.
Fiddle here (works in Chrome and Firefox):
https://jsfiddle.net/Josh_Shields/23kg3tf4/1/
Use document.querySelector('input[type = radio]:checked').value; to get value of selected checkbox , you can use other attributes to get value like name = gender etc. please go through below snippet definitely it will helpful to you,
Solution
document.mainForm.onclick = function(){
var gender = document.querySelector('input[name = gender]:checked').value;
result.innerHTML = 'You Gender: '+gender;
}
<form id="mainForm" name="mainForm">
<input type="radio" name="gender" value="Male" checked/>Male
<input type="radio" name="gender" value="Female" />Female
<input type="radio" name="gender" value="Others" />Others
</form>
<span id="result"></span>
Thank-You
HTML CODE:
<input type="radio" name="rdoName" value="YES"/>
<input type="radio" name="rdoName" value="NO"/>
JQUERY CODE:
var value= $("input:radio[name=rdoName]:checked").val();
$("#btnSubmit").click(function(){
var value=$("input:radio[name=rdoName]:checked").val();
console.log(value);
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="rdoName" value="YES"/> YES
<input type="radio" name="rdoName" value="NO"/> NO
<br/>
<input type="button"id="btnSubmit"value="Which one Selected"/>
You will get
value="YES" //if checked Radio Button with the value "YES"
value="NO" //if checked Radio Button with the value "NO"
Shortest
[...rates.children].find(c=>c.checked).value
let v= [...rates.children].find(c=>c.checked).value
console.log(v);
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
In Javascript we can get the values by using Id's "getElementById()" in the above code you posted has contain name not Id
so you to modify like this
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
use this rate_value according to your code
A year or so has passed since the question was asked, but I thought a substantial improvement of the answers was possible. I find this the easiest and most versatile script, because it checks whether a button has been checked, and if so, what its value is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check radio checked and its value</title>
</head>
<body>
<form name="theFormName">
<input type="radio" name="theRadioGroupName" value="10">
<input type="radio" name="theRadioGroupName" value="20">
<input type="radio" name="theRadioGroupName" value="30">
<input type="radio" name="theRadioGroupName" value="40">
<input type="button" value="Check" onclick="getRadioValue('theRadioGroupName')">
</form>
<script>
function getRadioValue(groupName) {
var radios = theFormName.elements[groupName];
window.rdValue; // declares the global variable 'rdValue'
for (var i=0; i<radios.length; i++) {
var someRadio = radios[i];
if (someRadio.checked) {
rdValue = someRadio.value;
break;
}
else rdValue = 'noRadioChecked';
}
if (rdValue == '10') {
alert('10'); // or: console.log('10')
}
else if (rdValue == 'noRadioChecked') {
alert('no radio checked');
}
}
</script>
</body>
</html>
You can also call the function within another function, like this:
function doSomething() {
getRadioValue('theRadioGroupName');
if (rdValue == '10') {
// do something
}
else if (rdValue == 'noRadioChecked') {
// do something else
}
}
Assuming your form element is referred to by myForm variable below, and that your radio buttons share the name "my-radio-button-group-name", the following is pure JavaScript and standards compliant (although I have not checked it to be available everywhere):
myForm.elements.namedItem("my-radio-button-group-name").value
The above will yield the value of a checked (or selected, as it is also called) radio button element, if any, or null otherwise. The crux of the solution is the namedItem function which works with radio buttons specifically.
See HTMLFormElement.elements, HTMLFormControlsCollection.namedItem and especially RadioNodeList.value, as namedItem usually returns a RadioNodeList object.
(I use MDN because it allows one to track standards compliance, at least to a large degree, and because it is easier to comprehend than many WhatWG and W3C publications)
directly calling a radio button many times gives you the value of the FIRST button, not the CHECKED button. instead of looping thru radio buttons to see which one is checked, i prefer to call an onclick javascript function that sets a variable that can later be retrieved at will.
<input type="radio" onclick="handleClick(this)" name="reportContent" id="reportContent" value="/reportFleet.php" >
which calls:
var currentValue = 0;
function handleClick(myRadio) {
currentValue = myRadio.value;
document.getElementById("buttonSubmit").disabled = false;
}
additional advantage being that i can treat data and/or react to the checking of a button (in this case, enabling SUBMIT button).
You can also loop through the buttons with a forEach-loop on the elements
var elements = document.getElementsByName('radioButton');
var checkedButton;
console.log(elements);
elements.forEach(e => {
if (e.checked) {
//if radio button is checked, set sort style
checkedButton = e.value;
}
});
An improvement to the previous suggested functions:
function getRadioValue(groupName) {
var _result;
try {
var o_radio_group = document.getElementsByName(groupName);
for (var a = 0; a < o_radio_group.length; a++) {
if (o_radio_group[a].checked) {
_result = o_radio_group[a].value;
break;
}
}
} catch (e) { }
return _result;
}
My take on this problem with pure javascript is to find the checked node, find its value and pop it out from the array.
var Anodes = document.getElementsByName('A'),
AValue = Array.from(Anodes)
.filter(node => node.checked)
.map(node => node.value)
.pop();
console.log(AValue);
Note that I'm using arrow functions.
See this fiddle for a working example.
You can use .find() to select checked element:
var radio = Array.from(document.querySelectorAll('#rate input'))
var value = radio.length && radio.find(r => r.checked).value
Here is a solution putting the radio buttons in a constant and getting the selected value only when needed.
const rates = document.forms.rates.elements["rate"]
showRate()
function showRate(){
document.getElementById('results').innerHTML = rates.value
}
<form id="rates" onchange="showRate()">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</form>
<div id="results"></div>
If you are using jQuery:
$('input[name="rate"]:checked').val();
<form id="rates">
<input type="radio" name="rate" value="Fixed Rate"> Fixed
<input type="radio" name="rate" value="Variable Rate"> Variable
<input type="radio" name="rate" value="Multi Rate" checked> Multi
</form>
then...
var rate_value = rates.rate.value;
check value by ID:
var CheckedValues = ($("#r1").is(':checked')) ? 1 : 0;
I used the jQuery.click function to get the desired output:
$('input[name=rate]').click(function(){
console.log('Hey you clicked this: ' + this.value);
if(this.value == 'Fixed Rate'){
rate_value = $('#r1').value;
} else if(this.value =='Variable Rate'){
rate_value = $('#r2').value;
} else if(this.value =='Multi Rate'){
rate_value = $('#r3').value;
}
$('#results').innerHTML = rate_value;
});
Hope it helps.
If the buttons are in a form
var myform = new FormData(getformbywhatever);
myform.get("rate");
QuerySelector above is a better solution. However, this method is easy to understand, especially if you don't have a clue about CSS. Plus, input fields are quite likely to be in a form anyway.
Didn't check, there are other similar solutions, sorry for the repetition
var rates = document.getElementById('rates').value;
cannot get values of a radio button like that instead use
rate_value = document.getElementById('r1').value;
If you are using the JQuery, please use the bellow snippet for group of radio buttons.
var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();
Simply use: document.querySelector('input[rate][checked]').value
https://codepen.io/anon/pen/YQxbZJ
The HTML
<div id="rates">
<input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="x2" name="rate" value="Variable Rate"
checked="checked"> Variable Rate
<input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>
<button id="rdio"> Check Radio </button>
<div id="check">
</div>
The JS
var x ,y;
var x = document.getElementById("check");
function boom()
{
if (document.getElementById("x1").checked)
y = document.getElementById("x1").value;
else if(document.getElementById("x2").checked)
y = document.getElementById("x2").value;
else if (document.getElementById("x3").checked)
y = document.getElementById("x3").value;
else
y = "kuch nhi;"
x.innerHTML = y;
}
var z = document.getElementById('rdio');
z.addEventListener("click", boom);`
var rates=document.getElementsByName("rate");
for (i = 0; i < rates.length; i++) {
if (rates[i].checked) {
console.log(rates[i].value);
rate=rates[i].value;
document.getElementById("rate").innerHTML = rate;
alert(rate);
}
}
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
</br>
<div id='rate'>
</div>
In php it's very easy
html page
Male<input type="radio" name="radio" value="male"><br/>
Female<input type="radio" name="radio" value="female"><br/>
Others<input type="radio" name="radio" value="other"><br/>
<input type="submit" value="submit">
Take value from form to php
$radio=$_POST['radio'];<br/>
use php if(isset($_POST['submit']))<br/>
{<br/>
echo "you selected".$radio."thank u";<br/>
}

Categories

Resources