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;
}
}
}
Related
I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.
I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)
not exactly what i have, but...
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
and in JS i have...
var rdObj = document.getElementByName("radioGrp");
var selectedValue;
for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
alert("Select one option");
return false;
}else{
//do something with value of radio checked value
}
}
This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.
Any hel will be very appreciated
You probably want to wait for an event before you do any sort of value checking, otherwise your script will only run once, and at this point in time, nothing would have ever had the chance be checked.
You can attach a change event listener to each of your radios...
var myRadios = document.querySelectorAll('[name=radioGrp]');
var selectedValue;
myRadios.forEach(radio => {
radio.addEventListener('change', changeHandler);
})
function changeHandler(evt) {
// do some check in here
console.log(evt.target.value)
}
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
...or you can attach a submit event handler to your form and do some checking of your data then.
const myForm = document.querySelector('form');
myForm.addEventListener('submit', submitHandler);
function submitHandler(evt) {
evt.preventDefault();
const data = new FormData(evt.target);
const optionVal = data.get('radioGrp');
// do some check in here
if (!optionVal) {
console.log(`Please select a value`)
} else {
console.log(`Thanks for selecting ${optionVal}`)
}
}
<form>
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
<input type="submit">
</form>
You can try this:
function validateForm() {
var radios = document.getElementsByName("radioGrp");
var formValid = false;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
formValid = true;
break;
}
}
if (!formValid) {
alert("Select one option");
}
return formValid;
}
<form name="form1" action="#" onsubmit="return validateForm();" method="post">
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
<br>
<input type="submit" value="Submit">
</form>
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);
}
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.
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])
}
}
i am geting undefined for ans . why? what is wrong?
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var ansVal = myForm.ans.value;
var qnoVal = myForm.qno.value;
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
<form nam="quiz" id="quiz" >
Yes:
<input type="radio" id="ans" name="ans" value="1" />
<br />No:
<input type="radio" id="ans" name="ans" value="0" />
<input id="qno" type="text" name="qno " value="qqq" />
<input type="button" value="" onClick="submitAnswer(); " />
</form>
Using theForm.inputElement is not standard and can't be guaranteed to work. Instead, you should use document.getElementById, or some other DOM mechanism, to find the input element you want. theForm.elements[name] also works.
You'll also need to fix your element IDs before you can do that - you have two <input type="radio" /> elements with an ID "ans", which is incorrect. IDs must be unique:
<input type="radio" id="ans1" name="ans" value="1" />
<input type="radio" id="ans2" name="ans" value="0" />
<script type="text/javascript">
var ans1 = document.getElementById('ans1');
var ans1value = ans1.value;
</script>
Or, get the radio button group as a single element using elements:
<script type="text/javascript">
var theForm = document.getElementById('quiz');
var ansValue = theForm.elements['ans'].value;
</script>
You have two elements with the same ID, causing a name conflict. They're also the same as the name attribute on the same element, which could cause some confusion down the road.
Try:
var ansVal = myForm.ans.checked;
This will work:
function submitAnswer() {
var myForm = document.getElementById('quiz');
// Set a default value, in case no radio button is selected
var ansVal = 'default value here';
var qnoVal = myForm.qno.value;
// Loop through radio buttons, getting the value of the
// one that is checked (selected).
var radioButtons = myForm.ans;
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
ansVal = radioButtons[i].value;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
this will work too
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var qnoVal = myForm.qno.value;
var ansVal = 'none';
for( i = 0; i < myForm.ans.length; i++ )
{
if( myForm.ans[i].checked == true )
{
ansVal = myForm.ans[i].value;
break;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
This will work
<html>
<form name="form">
Which one is good?<br>
<input type="radio" name="food" value="Spud"
checked="checked"> Spud<br>
<input type="radio" name="food" value="Carrot"> Carrot<br>
<input type="submit" onclick="get_radio_value()">
</form>
<script type="text/javascript>
<!--
function get_radio_value()
{
for (var i=0; i < document.form.food.length; i++)
{
if (document.form.food[i].checked)
{
var rad_val = document.form.food[i].value;
alert(rad_val);
}
}
}
//-->
</script>
</html>