I am working with a javascript function which takes the value of some questions using RadioButtons of YES or NO. To get the value of one question(Q1) I do something like this:
for (i=0; i<document.form1.Q1.length; i++){
if(document.form1.Q1[i].checked)
Array[0] = document.form1.Q1[i].value;
}
I have to do this for every question, so the code is getting very long. So I am trying to make a function or a loop in which the name of the question is changing. My only problem is that i dont know how to use a Variable on document.form1.VARIABLE.value. I already tried some ways but didnt work.
Can anyone help me with this?
Thanks a lot!
use
document.forms['form-name']['radio-button-name'].value
and give radio button names like que_1 que_2 so you can change that with i using string concatenation
Here's a loop that will traverse your radio buttons and build an array with the values. In the code and example, it's set for testing three questions (named Q1, Q2, and Q3). When done, the array "aux" contains the list of checked values:
var max = 3;
var aux = new Array();
function getCheckedValue(groupName) {
var radios = document.getElementsByName(groupName);
for (i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
return null;
}
function check() {
for(var i=1;i<=max;i++) {
//console.log(i,getCheckedValue('Q'+i));
aux[i-1] = getCheckedValue('Q'+i);
}
console.log(aux);
}
jsFiddle example.
Don't use radio buttons, use checkboxes instead (checked=yes, unchecked=no). Then you can iterate your checkboxes freely, and see what's checked and not. Striked out, OP needs the difference between "yes", "no" and "no answer".
After some extensive coding (my JS is rusty) I came up with the following:
<form name=form1 id=form1 action="index.php">
<p>Question 1</p>
<label><input type="radio" name="Q1" value="yes">Yes</label>
<label><input type="radio" name="Q1" value="no">No</label>
<p>Question 2</p>
<label><input type="radio" name="Q2" value="yes">Yes</label>
<label><input type="radio" name="Q2" value="no">No</label>
<p>Question 3</p>
<label><input type="radio" name="Q3" value="yes">Yes</label>
<label><input type="radio" name="Q3" value="no">No</label>
<button id="go">Go!</button>
</form>
<script type="text/javascript">
check = function (e) {
e.preventDefault(); //Don't submit!
var result = [];
var form = document.getElementById("form1");
for (var i = 1; typeof(form["Q" + i]) != "undefined"; i++) {
for (var j = 0; j < form["Q" + i].length; j++) {
if (form["Q" + i][j].checked) {
result.push(form["Q" + i][j].name + " " + form["Q" + i][j].value);
}
}
}
console.log(result);
}
button = document.getElementById("go");
button.onclick = check;
</script>
Triggered by clicking the "Go!" button.
The point is using the string concatenation of "Q" and i to get to "Q1" "Q2" etc.
Related
I am trying to write a form when I ask the user to write if they like to eat or not. However, no matter what they answer, the answer comes out "yes". What is the problem with this code?
<form>
Do you like food?<br>
<input type="radio" id="validate" value="yes">Yes<br>
<input type="radio" id="validate" value="no">No<br>
<br><br>
<input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood()">
</form>
<script>
function eatFood() {
var y = document.getElementById("validate").value;
alert(y);
}
</script>
Here is the most simple way to get a radio input value using JavaScript:
function eatFood() {
var choice = document.querySelector('input[name = validate]:checked').value;
alert(choice);
}
Working demo : https://codepen.io/andreds/pen/ppQzeL
Here is the a second way :
function eatFood() {
var radios = document.getElementsByName('validate');
for (var i = 0, length = radios.length; i < length; i++)
{
if (radios[i].checked)
{
alert(radios[i].value);
break;
}
}
}
Second way working demo : https://codepen.io/andreds/pen/XVyrJB
Here is third way, if you only have two radios input :
function eatFood() {
if (document.getElementById('yes').checked) {
result = document.getElementById('yes').value;
}
if (document.getElementById('no').checked) {
result = document.getElementById('no').value;
}
alert(result);
}
Third way working demo : https://codepen.io/andreds/pen/KZrPVy
You missed the name attribute, this is necessary to group radio buttons:
<input type="radio" name="validate" value="yes">Yes<br>
<input type="radio" name="validate" value="no">No<br>
The id must be unique, fixing the JavaScript function with this, the result would be the next (as André's answer):
function eatFood() {
var radios = document.getElementsByName('validate');
for (var i = 0, length = radios.length; i < length; i++)
{
if (radios[i].checked)
{
alert(radios[i].value);
break;
}
}
}
how to pass checkbox values in an array to a function using onclick in JavaScript.
following is my html code. Note that I don't use form tag. only input tags are used.
<input id="a"name="a" type="checkbox" value="1" checked="checked" >A</input>
<input id="a"name="a" type="checkbox" value="2" checked="checked" >B</input>
<input id="a"name="a" type="checkbox" value="3" checked="checked" >C</input>
<button onclick="send_query(????)">CLICK</button>
following is my JavaScript function
function send_query(check) {
var str = "";
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
str = str + check[i];
}
console.log(str);
}
You can write a onclick handler for the button, which can create an array of clicked checkbox values and then call the send_query with the parameter as shown below
<button onclick="onclickhandler()">CLICK</button>
then
function onclickhandler() {
var check = $('input[name="a"]:checked').map(function () {
return this.value;
}).get();
console.log(check);
send_query(check)
}
Note: I would also recommend using jQuery to register the click handler instead of using inline onclick handler.
Note: Also ID of elements must be unique in a document... you have multiple elements with id a, I'm not seeing you using that id anywhere so you could probably remove it
With pure javascript (demo) (tested with Chrome only).
HTML :
<button onclick="send_query(document.getElementsByTagName('input'))">
Javascript :
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}
Try this
<form name="searchForm" action="">
<input type="checkbox" name="categorySelect[]" id="1"/>
<input type="checkbox" name="categorySelect[]" id="2" />
<input type="checkbox" name="categorySelect[]" id="3"/>
<input type="button" value="click" onclick="send_query();"/>
</form>
JS
function send_query() {
var check = document.getElementsByName('categorySelect[]');
var selectedRows = [];
for (var i = 0, l = check.length; i < l; i++) {
if (check[i].checked) {
selectedRows.push(check[i]);
}
}
alert(selectedRows.length);
}
This may seem silly and downright stupid but I can't seem to figure out how to check the value of a radio button group in my HTML form via JavaScript. I have the following code:
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
How do I retrieve the value of gender via JavaScript?
Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).
document.querySelector('input[name="gender"]:checked').value
In pure Javascript:
var genders = document.getElementsByName("gender");
var selectedGender;
for(var i = 0; i < genders.length; i++) {
if(genders[i].checked)
selectedGender = genders[i].value;
}
update
In pure Javascript without loop, using newer (and potentially not-yet-supported) RadioNodeList :
var form_elements = document.getElementById('my_form').elements;
var selectedGender = form_elements['gender'].value;
The only catch is that RadioNodeList is only returned by the HTMLFormElement.elements or HTMLFieldSetElement.elements property, so you have to have some identifier for the form or fieldset that the radio inputs are wrapped in to grab it first.
If you are using a javascript library like jQuery, it's very easy:
alert($('input[name=gender]:checked').val());
This code will select the checked input with gender name, and gets it's value. Simple isn't it?
Live demo
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.
<form name="myForm">
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
</form>
<script>
var selected = document.forms.myForm.gender.value;
</script>
Try:
var selectedVal;
for( i = 0; i < document.form_name.gender.length; i++ )
{
if(document.form_name.gender[i].checked)
selectedVal = document.form_name.gender[i].value; //male or female
break;
}
}
Another solution for ES5+
[...document.getElementsByName("gender")].find(input => input.checked).value;
Without loop:
document.getElementsByName('gender').reduce(function(value, checkable) {
if(checkable.checked == true)
value = checkable.value;
return value;
}, '');
reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.
The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.
function myFunction() {
document.getElementById("text").value='male'
document.getElementById("myCheck_2").checked = false;
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myFunction_2() {
document.getElementById("text").value='female'
document.getElementById("myCheck").checked = false;
var checkBox = document.getElementById("myCheck_2");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
Male: <input type="checkbox" id="myCheck" onclick="myFunction()">
Female: <input type="checkbox" id="myCheck_2" onclick="myFunction_2()">
<input type="text" id="text" placeholder="Name">
I've two radio buttons to select a type of IVA:
<input type="radio" value="18" checked="true" name="ivacontract"> 18%
<input type="radio" value="16" name="ivacontract"> 16%
And I've one function that will calculate a value depending of the value of the radio button with name "ivacontract". In jQuery I'll use a selector and .val(); to get the value but this application (not coded by me) doesn't use jQuery so I don't know how to do it.
Any help?
Thank you in advance!
function getCheckedValues(objName)
{
var arr = new Array();
arr = document.getElementsByName(objName);
for(var i = 0; i < arr.length; i++)
{
var obj = document.getElementsByName(objName).item(i);
if(obj.checked)
{
alert(obj.value);
}
}
}
getCheckedValues("ivacontract");
Here is a working sample:
http://jsfiddle.net/eJBg9/1/
Try this:
function checkradio(fname,rname)
{
var radios=document[fname].elements[rname];
for(var i=0;i<radios.length;i++)
{
if(radios[i].checked)
return radios[i].value;
}
return false;
}
Where fname is your form name and rname is your radio buttons name that is in your code is ivacontract.
Hope this helps.
Also, here is an example of getting and setting a value for the radio buttons.
http://www.somacon.com/p143.php
<input type="radio" id="radio1" value="18" checked="true" name="ivacontract"> 18%
<input type="radio" id="radio2" value="16" name="ivacontract"> 16%
if (document.getElementById('radio1').checked==true) )
{
/// Your Code ///
}
Like the title says, what's the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio button is selected, so another way to phrase the question:
Given a string variable in JavaScript, how can I tell which exact radio button input element (if any) with that string as it's name is currently selected?
I'm not using jQuery. If you want to provide a jQuery answer, go ahead. Someone else might find it useful. But it won't help me and I won't upvote it.
You can use document.getElementsByName(), passing the name of the radio group, then loop over them inspecting the checked attribute, e.g. something like:
function getCheckedValue( groupName ) {
var radios = document.getElementsByName( groupName );
for( i = 0; i < radios.length; i++ ) {
if( radios[i].checked ) {
return radios[i].value;
}
}
return null;
}
getElementsByName didn't work for me. I did this:
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
if (radios[i].type == 'radio' && radios[i].checked) {
nbchecked++;
}
}
Use document.getElementsByName() is the short answer to the question you asked.
However, it may be better to do something like this:
<form name="formFoo">
Foo: <input type="radio" name="groupFoo" value="foo" checked> <br />
Bar: <input type="radio" name="groupFoo" value="bar"> <br />
Baz: <input type="radio" name="groupFoo" value="baz"> <br />
<input type="submit" >
</form>
Then use the JavaScript:
function getRadioValue(formName, groupName) {
var radioGroup = document[formName][groupName];
for (var i=0; i<radioGroup.length; i++) {
if (radioGroup[i].checked) {
return radioGroup[i].value;
}
}
return null;
}
By doing this, you avoid having to use a function that searches the entire document. It just searches first for the form, then within that form for controls with that same name. The problem here is that if you were to have a checkbox in the middle of the form with the same name, it could be returned instead of the correct radio value. If another type of control was thrown in with the same name, then it could cause an error. Both of these circumstances should probably be considered programmer error, but it wouldn't hurt for the function to be expanded to check for them, at some potential performance loss. Just change the line:
if (radioGroup[i].checked) {
to:
if (radioGroup[i].type=='radio' && radioGroup[i].checked) {
I'll bite for the jQuery answer
var selectedValue = $("input[name='radio_name']:checked").val();
var options = document.getElementsByName('myRadioButtons');
for(i = 0; i < options.length; i++)
{
var opt = options[i];
if(opt.type=="radio")
{
if(opt.checked)
{
}
}
}
<form name="myForm" id="myForm" action="">
<input type="radio" name="radioButton" value="c1">Choice 1
<input type="radio" name="radioButton" value="c2">Choice 2
</form>
<script>
var formElements = window.document.getElementById("myForm").elements;
var formElement;
var radioArray = [];
for (var i = 0, j = 0; i < formElements.length; i++) {
formElement = formElements.item(i);
if (formElement.type === "radio" && formElement.name === "radioButton") {
radioArray[j] = formElement;
++j;
}
}
alert(radioArray[0].value);
alert(radioArray[1].value);
</script>
$("input[type='radio'][name='xxxxx']:checked").val()
To get all radio buttons directly by name:
element.querySelectorAll("input[name='nameOfTheName']")
The querySelectorAll() method can be used to get elements of a certain type by name. There are advantages to using querySelectorAll compared to getElementsByName() in certain situations. If you use getElementsByName on anything other than document, you will get an error:
element_Name_Here.getElementsByName is not a function
But querySelectorAll() can be used on sub elements of the document. This is helpful when you want to get one element out of multiple elements that all have the same structure (Rows in a list). In that case, you might not want to try to give separate ID's to every row. In that situation, the function called can be passed this, get the parentNode and from the parent, search for a specific attribute. This avoids needing to search the entire document.
html
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
script
function getOnlyThisRowsRadios(thiz) {
var i,L,parentElement,radioButtons;
parentElement = thiz.parentNode;//Get the parent of the element
radioButtons = parentElement.querySelectorAll("input[name='nameOfTheName']");
console.log('radioButtons: ' + radioButtons)
L = radioButtons.length;
console.log('L: ' + L)
for (i=0;i<L;i++) {
console.log('radBttns[i].checked: ' + radBttns[i].checked)
radBttns[i].checked = false;//Un-check all checked radios
}
This definitely works if your name attribute is taken for something else.
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
if (radios[i].type == 'radio' && radios[i].checked) {
console.log(radios[i])
}
}