Value of radio button - javascript

This is my code:
<script>
function myFunction() {
var x;
x = document.getElementById("numb2").value;
document.write(x);
}
</script>
***
<body>
<form>
<input id = "numb2" value = "Male" type="radio">Male
<input id = "numb2" value= "Female" type="radio">Female
</form>
</body>
The problem is that I'm getting 'Male' whatever I choose.

Check this fiddle:
<form>
<input name='sex' value = "Male" type="radio">Male
<input name='sex' value= "Female" type="radio">Female
</form>
You must use name property to achieve this functionality and loop over all elements to check which radio element is selected, as shown in below code.
function myFunction() {
var value = "NONE";
var elems = document.getElementsByName("sex");
for(var i = 0; i < elems.length; i++) {
if(elems[i].checked) {
value = elems[i].value;
break;
}
}
alert(value);
}

First, you need to create a button group by giving both buttons the same name. Then you can use querySelector to select the chosen element and get its value.
function myFunction() {
var val = document.querySelector("[name=numb2]:checked").value;
document.getElementById("output").innerHTML = val;
}
document.getElementById("button").addEventListener("click", myFunction);
<input name = "numb2" value = "Male" type="radio">Male
<input name = "numb2" value = "Female" type="radio">Female
<div>
Chosen: <span id="output"></span>
</div>
<button id="button">Click</button>

first you must add the radio buttons in a group, you can do that with the attribute "name". Let me show you how to do that.
<input type="radio" name="groupRadio" value="male">Male
<input type="radio" name="groupRadio" value="female">Female

Related

Alert Radio Input in form

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;
}
}
}

Setting user input from html to value in google sheets with GAS

I have HTML code with some JS as follows:
<form>
Object: <input type="text" name="object">
<br>
brand: <input type="text" name="brand">
<br>
<br>
color: <input type="text" name="color">
<br>
<input type="submit" value="Submit"onclick="doTest()">
</form>
<h3>Results</h3>
formValues.object = <span id="object"></span><br>
formValues.brand = <span id="brand"></span><br>
formValues.color = <span id="color"></span><br>
<script id="jsbin-javascript">
var formValues = {};
function inputObj(formNR, defaultValues) {
var inputs = formNR.getElementsByTagName('input');
for ( var i = 0; i < inputs.length; i++) {
formValues[inputs[i].name] = defaultValues[i];
if(inputs[i].type === 'text') {
inputs[i].value = defaultValues[i];
document.getElementById(inputs[i].name).innerHTML = defaultValues[i];
}
inputs[i].addEventListener('keyup', function() {
formValues[this.name] = this.value;
document.getElementById(this.name).innerHTML = this.value;
}, false);
}
}
var defValues =['','',''];
inputObj(document.forms[0], defValues);
</script>
When the user inputs some text, this text becomes a variable. E.g there is a variable called "formValues.object". Then I want to take the value of this variable and write it onto a google sheet using the following code
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(" ");
}
The problem is that since the data I want to enter is a variable I do not know what I have to put between the .setValue brackets in order for the data the variable stores to appear in cell I2 of the google sheet when the submit button is pressed (I have already figured out how to link the submit button with the function).
If your value is an object and you want to put it into a single cell you will need to convert the variable to a string.
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(JSON.stringify(MyVariable));
}

5 radio buttons fill up randomly?

Hi I am trying to make five buttons as you can see and I want a function when you push "click me" it will fill up the five button randomly.
It's like a random generator for stats for a game.
I don't know if I'm doing it all wrong but I think I need some other coding for this.
Can anyone that can help me?
This is what I have:
<button onclick='myFunction()'>click me</button>
<div id="demo">
<Input type = radio Name = r1>
<Input type = radio Name = r2>
<Input type = radio Name = r3>
<Input type = radio Name = r4>
<Input type = radio Name = r5>
</div>
<script type="text/javascript">
function myFunction() {
document.getElementById('demo').innerHTML = '';
var num = 3;
var noOfButtons = Math.floor(Math.random() * num);
console.log(noOfButtons);
for (var i = 0; i < noOfButtons; i++) {
var box = document.createElement();
document.getElementById('demo');
}
}
</script>
not exactly sure what your looking for. I threw this JSFiddle together. Take a look and see if its what you're looking for.
<button id='button1'>click me</button>
<div id="demo">
<input type='radio' id='r1'>
<input type='radio' id='r2'>
<input type='radio' id='r3'>
<input type='radio' id='r4'>
<input type='radio' id='r5'>
</div>
.
var button1 = document.getElementById('button1');
button1.onclick = function () {
var noOfButtons = 5;
var pick = Math.floor(Math.random() * noOfButtons) + 1;
var radioBtn = document.getElementById('r' + pick);
radioBtn.checked = true;
}
[edit]
I think what you're trying to do is randomly check a finite number of radios, in which case there's no need to set demo's html to ''. I added the class myRadios to the tags of your radios (just in case there are other radios on the page that you don't want to include in the random checking), and then used the following function:
function myFunction() {
var radios = document.getElementsByClassName('myRadios');
for (var i=0; i<radios.length; i++)
{
radios[i].checked = ( (Math.random()*10) > 5) ? true : false;
}
}
Here is a a working fiddle. Let me know if this is the functionality you were looking for or if you have any questions about how it works :)

Checking Value of Radio Button Group via JQUERY?

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">

Undefined value, reading an input

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>

Categories