Javascript add cookie - javascript

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

Related

Checkboxes and localStorage

I have a list of tasks if you will and I am trying to create checkboxes that persist next to each when I go back to the page but closing the browser or hard refresh kills my selections. I have found code for saving a single checkbox but how do I iterate through the different boxes and keep them next time I enter? It seems like a really simple process but I am super-new to javascript... I could do this easily in vbscript but I would like it to work everywhere and not just IE!
New to all this so be gentle please.
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
function save() {
//enter iteration sequence
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>
To retrieve all elements you can use document.querySelectorAll and pass as argument the filter that will do the job. In this case you want to retrieve all htlm elements that have the type attribute value equals to checkbox. After the retrieval of all elements that have type="checkbox", you should traverse all elements of list. And for each element you should store the id of checkbox as key and the checked of the checkbox asvalue in localstorage.
Below is the code:
<script>
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
And below is the code for updating the checkboxes with value we stored in localstorage.
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
If you want to use cookie to store the information instead of local storage. Link for more information: https://www.guru99.com/cookies-in-javascript-ultimate-guide.html.
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
VERSION WITH LOCAL STORAGE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
</body>
</html>
VERSION WITH COOKIE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(accessCookie(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
createCookie(el.id, el.checked,1);//1 is the day to expire
console.log(el.id,el.checked);
})
}
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
</script>
</body>
</html>
Just pass a different id in to document.getElementById.
Make sure to use a different key for localStorage.setItem so you don't overwrite a different value.
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
You could do this individually for each item or you could get all the elements of a specific class. Then loop through the elements and use their id as the local storage key.
Alternatively you could use a for loop and loop for as many items as you wish to save
On every save you can create an object with checkbox identification and values, save t in localStorage, on reloading, get the the whole object by a single key, parse it, loop through and set values
function save() {
//enter iteration sequence
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var obj = {};
for (i = 0; i < checkboxes.length; i++) {
obj[checkboxes[i].id] = checkboxes[i].checked
}
localStorage.setItem("box", JSON.stringify(obj));
}
//for loading...
var checkboxesValues = JSON.parse(localStorage.getItem("box"));
Object.keys(checkboxesValues).map(key => document.getElementById(key).checked = checkboxesValues[key]);
Your code works well too if you pass right id's of inputs but there is an issue with it that for each and every input you have to add there variable you also can use for loop for that.
Your code with fixing script
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="button" value="Save" onclick="save();" />
<script>
function save() {
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checkbox2 = document.getElementById("whatever-2");
localStorage.setItem("whatever-2", checkbox2.checked);
}
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
var checked = JSON.parse(localStorage.getItem("whatever-2"));
document.getElementById("whatever-2").checked = checked;
</script>

How to retain the last existing text on the input field using JavaScript?

Good day everyone, my instructor gave me an assignment on checkboxes and input fields, he wants the input field to be disabled on default, and open the field once the corresponding checkbox is checked and store the value on that field, and if I un-check the box again, the field should be clear and if I check the same box again, the last input value on the field should show again. I am able to succeed but I found a bug I can't solve, if I check an empty box, my previous stored value from the field becomes null again. I already put my variable in global scope but still the variable becomes null. (sorry for my english).
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="checkbox" id="check1" onclick="send()">
<input type="text" id="input1" disabled><br>
<input type="checkbox" id="check2" onclick="send()">
<input type="text" id="input2" disabled><br>
<script>
var val1 = null;
var val2 = null;
function send() {
var check1 = document.getElementById('check1').checked;
var check2 = document.getElementById('check2').checked;
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if(check1) {
input1.disabled = false;
input1.value = val1;
} else {
input1.disabled = true;
val1 = document.getElementById('input1').value;
input1.value = null;
}
if(check2) {
input2.disabled = false;
input2.value = val2;
} else {
val2 = document.getElementById('input2').value
input2.disabled = true;
input2.value = null;
}
}
</script>
</body>
</html>
The problem in your case is that you are handling boths checkboxes together, you need to seperate the processing so that all your checkbox/input combinations are independant from one another.
I altered the send function to take parameters and update the corresponding nodes accordingly and updated your HTML to fit.
// create data in which values have keys as the IDs of the inputs
var data = {
input1: null,
input2: null
};
function send(checkboxId, inputId) {
// get checkbox and input
let checkbox = document.getElementById(checkboxId);
let input = document.getElementById(inputId);
// handle checkbox and input state
input.disabled = !checkbox.checked;
if (checkbox.checked) {
input.value = data[inputId];
}
else {
data[inputId] = input.value;
input.value = null;
}
}
<input type="checkbox" id="check1" onclick="send('check1', 'input1')">
<input type="text" id="input1" disabled><br>
<input type="checkbox" id="check2" onclick="send('check2', 'input2')">
<input type="text" id="input2" disabled><br>
Hope this helps.
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="checkbox" id="check1" onclick="sending(this.checked, 1)">
<input type="text" id="input1" disabled onblur="store(this.value, 1)"><br>
<input type="checkbox" id="check2" onclick="sending(this.checked, 2)">
<input type="text" id="input2" disabled onblur="store(this.value, 2)"><br>
<script>
var val1 = null;
var val2 = null;
function sending(isChecked, which) {
var check = which === 1 ? 'input1' : 'input2';
var field = document.getElementById(check);
if (!isChecked) {
field.value = null;
} else {
field.value = which === 1 ? val1 : val2;
}
field.disabled = !isChecked;
}
function store(val, which) {
if (which === 1) {
val1 = val;
} else {
val2 = val;
}
}
</script>
</body>
</html>

Issue changing innerHTML of basic HTML/Javascript page

I have an HTML/Javascript document that outputs the grade of a student based on the inputs of my form. The mechanics of the grade calculation should be working, but the final output does not. The main thing I'm honing in on is the document.getElementById("span1").innerHTML and span2's same code. I want these to change the inner HTML to the values I calculated with my code, but they remain at X and yy even when I attempt to change them.
I think the error should be in my calculateGrade function or in my HTML. I did not include the rest of the code to simplify my post, so the error lay outside of where I think it does. I need the output paragraph to have the correct values, but they are not being changed.
Even if I change the new innerHTML values to concrete values such as P and 88, the code displays X and yy instead. I set a default "A" and "91" to test it and receive the same problem. I think there may be an issue with my form gets as changing the value of the name in the form also doesn't change my final output.
This is my first Javascript/HTML project, and I'm very desperate to get it working. I'm already one day late, and in a couple hours, it will be two. I deeply appreciate any hep I can get. Thanks guys. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
alert(document.getElementById("FirstName").value);
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
var grade = "A";
var score = 91;
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
return false;
}
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1" onsubmit="calculateGrade()" style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="submit" value="Submit">
</form>
<p id="p1" style="display:none">
Final course grade for
<span id="fname">Joe</span> <span id="lname">Peterson</span>
is: <span id="span1">X</span> (<span id="span2">yy</span>%)
</p>
</body>
</html>
Just move the alert call to the end of the function, and it will work finely:
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
var grade = "A";
var score = 91;
document.getElementById("span1").innerHTML = grade;
document.getElementById("span2").innerHTML = score;
document.getElementById("fname").innerHTML = fname;
document.getElementById("lname").innerHTML = lname;
alert(document.getElementById("FirstName").value);
return false;
}
And set your form action to return calculateGrade() as Patrick Evans mentioned in his comment.
here's a demo
And as
Like this should be ok...I only change the input type to "button"
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
alert(document.getElementById("FirstName").value);
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
var grade = "A";
var score = 91;
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
document.getElementById("p1").style.display = "block";
return false;
}
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1"style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="button" value="Submit" onclick="calculateGrade()">
</form>
<p id="p1" style="display:none">
Final course grade for
<span id="fname">Joe</span> <span id="lname">Peterson</span>
is: <span id="span1">X</span> (<span id="span2">yy</span>%)
</p>
</body>
</html>

jQuery or Javascript to parse querystring on submit

This form has multiple choices through a checkbox. Eg. Pet You Own is a multiple choice and there are various options such as Cat, Dog, Mule etc.
Now by default, the querystring sent will look like:
?pet=dog&pet=cat&pet=mule
given all 3 are checked.
I need a way to parse this so that the querystring looks like:
?pet=dog,cat,mule
Another requirement is that, there are other parameters/inputs in the form so it needs to work in conjunction with other standard form inputs.
The format you're currently seeing is the conventional format. If your form fields were named pet[] rather than pet, your server would be able to interpret the result as an array.
Having said that, to actually do what you're requesting, you could reset the name attribute of your checkboxes, so that they won't be posted, and instead post a hidden field that holds the value of your checkboxes as a comma separated string:
$('#my-form').submit(function() {
var pets = [];
$('input[name=pet]:checked').each(function() {
pets.push($(this).val());
});
// stop checkboxes from being posted
$('input[name=pet]').attr('name','');
// have an input field be posted instead
$('#my-hidden-field')
.val(pets.join(','))
.attr('name', 'pet');
});
A bit of cleaning is needed but using this with plain JS you can acheive
<html>
<head>
<title>My Page</title>
<script>
function myFunction(){
var options = "";
if(document.getElementById("option1").checked){
options = options+"Milk";
}
if(document.getElementById("option2").checked){
options = options+",Butter";
}
if(document.getElementById("option3").checked){
options = options+",Cheese";
window.location = "end.html&options="+options
}
}
</script>
</head>
<body>
<div align="center"><br>
<input id="option1" type="checkbox" name="option1" value="Milk"> Milk<br>
<input id="option2" type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input id="option3" type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
Button to submit
</body>
</html>
I suggest you to do this job on server side. When your server receive this request, it will get an array which is called pet and has three element: dog,cat and mule. you can conjunction them easily.
====
I implement this with JavaScript:
var str = window.location.href;
var queryString = "", temp = {};
str = str.substring(str.lastIndexOf("?") + 1);
str.split("&").some(function(item) {
var tarr = item.split("=");
if(typeof temp[tarr[0]] == "undefined") {
temp[tarr[0]] = tarr[1];
} else if(typeof temp[tarr[0]] == "string") {
temp[tarr[0]] += "," + tarr[1];
}
});
// Make queryString
for(var i in temp) {
queryString += "&" + i + "=" + temp[i];
}
queryString = queryString.replace(/^./,"");
//
var href = window.location.href;
console.log("before:", href);
href = href.replace(/\?.*$/, "?");
// the url is that you want
console.log("after:", href + queryString);
//window.location.href = href + queryString;
OUTPUT:
before:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog&pet=cat&pet=mule&animal=camel
after:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog,cat,mule&animal=camel
Name your check boxes as p1, p2 etc. Have a hidden field in your form named 'pet'. Just before submit using JS, set the value of your hidden variable the way you need and return true.
function beforeSubmit() {
var p = '';
if($('#p1').attr('checked')==true) p += ',cat';
if($('#p2').attr('checked')==true) p += ',dog';
...
p = p.substring(1); // strip the , at 0
$('#pet').val(p);
return true;
}
and your form should be like:
<form ... onsubmit="return beforeSubmit()">
...
<input type="checkbox" name="p1" id="p1">Cat<br>
<input type="checkbox" name="p2" id="p2">Dog<br>
...
<input type="hidden" name="pet" id="pet" value="">
</form>

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