Undefined value, reading an input - javascript

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>

Related

Value of radio button

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

Javascript add cookie

I am fairly new to javascript and not really sure what I am doing. Right now I am trying to add textbox data as well as some strings to cookies to display on another page. The textbox part is working.
For the strings, I am taking the value of a radio button (for a multiple choice quiz validation) and if the value is the correct value for that group, I would like to add a string to cookies. I can't figure out what I am doing wrong for this part.
Specifically what isn't working is the content in the gradeit() function
JS file
var total = 5;
var right = 0;
//cookies
function addToCookie(id, value)
{
document.cookie = id + escape(value);
}
var grade=new Array()
function gradeit(){
if(document.getElementById('correctOne').checked)
{
right++;
addToCookie("Q1 - Correct",right);
}
else {addToCOokie("Q1 - Incorrect", right);}
}
function checkCookie() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
addToCookie("First Name= ",firstName);
addToCookie("Last Name= ",lastName);
addToCookie("Email=",email);
}
window.onload = function () {
var elem = document.getElementById("submit");
elem.addEventListener('click', checkCookie);
}
// determine whether there is a cookie
var allcookies = document.cookie;
alert("All Cookies : " + allcookies);
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
var result = "";
// Now take key value pair out of this array
for (var i = 0; i < cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
result +=( name + " is : " + value)+"<br>";
}
document.writeln(result);
HTML PAge
<DOCTYPE HTML5>
<html>
<head>
<meta charset="utf-8">
<title>Quiz</title>
<script src="cookies.js" type="text/javascript"></script>
</head>
<body>
<h1><b>Multiple Choice Quiz</b></h1>
<form name="myquiz" action="answers.html" method="post">
<h2>Please Enter the Following:</h2>
First Name: <input type="text" id="fname"></input>
Last Name: <input type="text" id="lname"></input><br><br>
Student Email: <input type="email" id="email"></input>
<br>
<h3>#1. What is the capital of Iowa?</h3>
<input type="radio" name="question1" id="correctOne">Des Moines</input>
<input type="radio" name="question1" id="wrong">Los Angeles</input>
<input type="radio" name="question1" id="wrong">Paris</input>
<input type="radio" name="question1" id="wrong">Tokyo</input>
<br><br>
<input type="submit" id="submit" value="Submit Answers" onClick="gradeit()"></input>
</form>
</body>
</html>
I just got it to work by modifying my gradeit() function this way:
function gradeit(){
var ans = "";
if(document.getElementById('correctOne').checked)
{
//document.getElementById("output").innerHTML = "Q1 - Correct";
right++;
ans ="Right";
addToCookie("Q1 - ", ans);
}
else {
ans ="Wrong";
addToCookie("Q1 - ", ans);
}
}

how to pass checkbox values in an array to a function using onclick in javascript

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

javascript how to add textboxs' values and titles to textarea

I have this html:
<input type="radio" name="r1" value="v1"><input name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2"><input name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1">
<textarea rows=6 cols=80 name="conclus" id="idConclus">
</textarea><br><br>
Is there a way on js to fill textarea with titles and values of inputs by selecting some of them and clicking a button?
e.g.: "text1 - value1, text2 - value2" etc.
thanks for material.
mmm... Felix King, in your examples the button updates the form. and if i need to put one testfield 1, then put some text in textarea manually, and then again textfield 2 and so on? i mean, without updating the textarea?
getElementById is your friend :-)
<script>
getValues = new function() {
var myTextArea = document.getElementById('idConclus');
var radio1 = document.getElementById('asd1');
var radio2 = document.getElementById('asd2');
myTextArea.value = radio1.title + ' - ' + radio1.value + ' ,'
+ radio2.title + ' - ' + radio2.value;
}
</script>
<input type="radio" name="r1" value="v1">
<input type="text" name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2">
<input type="text" name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1" handler = getValues>
I suggest you read about JavaScript and forms.
Assuming you have this HTML:
<form name="data">
<input name="asd1" title="text1" id="asd1"><br>
<input name="asd2" title="text2" id="asd2"><br>
<input type="button" name="but1" value="update">
<textarea rows=6 cols=80 name="conclus" id="idConclus"></textarea>
</form>
you can do this:
var inputs = ['asd1', 'asd2'];
var form = document.data;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
var input = form[inputs[i]];
text.push(input.title + " - " + input.value);
}
textarea.value = text.join(' ');
}, false);​
See a live example here: http://jsfiddle.net/6kbtH/
Update:
If you want to control which values are put into the textbox, I would use checkboxes, give them the same name and the name of the input as value like so:
<input type="checkbox" name="take" value="asd1"><input name="asd1" title="text1" id="asd1">
<input type="checkbox" name="take" value="asd2"><input name="asd2" title="text2" id="asd2">
Then you can loop with nearly the same code over those values:
var form = document.data;
var inputs = form.take;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
if(inputs[i].checked) {
var input = form[inputs[i].value];
text.push(input.title + " - " + input.value);
}
}
textarea.value = text.join(' ');
}, false);​
Live example: http://jsfiddle.net/sJdqb/
Note: You have to take care of cross-browser issues regarding attaching the event listener yourself if you don't use a JavaScript library. The examples I gave will work in Firefox and WebKit-based browsers.

In JavaScript, how can I get all radio buttons in the page with a given name?

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])
}
}

Categories