Why I'm getting undefined error in Firefox and IE. This code works well in Google Chrome. Here is the full code http://liveweave.com/fUhpiI
this is my html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="css/hpstyles.css" rel="stylesheet">
<script src="js/hpjs.js"></script>
</head>
<body>
<form id="hp">
<div>
<h2>1. Which one do you prefer?</h2>
<div>
<input type="radio" name="q1" id="radio1" class="radio" value="9"/>
<label for="radio1">Tea</label>
</div>
<div>
<input type="radio" name="q1" id="radio2" class="radio" value="4"/>
<label for="radio2">Coffee</label>
</div>
<div>
<input type="radio" name="q1" id="radio3" class="radio" value="1"/>
<label for="radio3">Milk</label>
</div>
</div>
<div>
</br>
<div><div>
<button type="button" onclick="hp(this.form)">Check</button>
<input class="reset" type="reset" value="Reset">
</div></div></div>
</form>
<div id="result"></div>
<div id="total"></div>
</body>
</html>
this is javascript
function hp(form)
{
var count1=0, count2=0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0,a ;
for(var i=0;i<3;i++){
if (form.q1[i].checked === true)
{
count1++;
}
}
if(count1!==1){
alert("Please Answer 1st Question");
return false;
}
answer1 = (form.q1.value);
a=Math.floor(answer1);
document.getElementById("result").innerHTML= "The selected values are "+"</br>"+answer1;
}
you should declare a answer variable .and you should access "q1" elements by giving index since you have 3 "q1" elements .basically form.q1 is a object NodeList .you can't get value from object NodeList.so actually in your case you should add brake to for loop and find the clicked radio button index .
you should use
answer1 = form.q1[i].value;
instead of
answer1 = form.q1.value;
explain
form.q1 is a object NodeList so
form.q1.value --> undefined since object NodeList/collection has no property "value"
and
form.q1[0] --> HTMLInputElement so
form.q1[0].value --> is not undefined
fixed code .WORKING DEMO http://jsfiddle.net/madhawa11111/3rywkdvf/
function hp(form) {
var i;
var answer;
var count1 = 0,count2 = 0,count3 = 0,count4 = 0,count5 = 0,count6 = 0,count7 = 0,count8 = 0,count9 = 0,count10 = 0, a;
for (i = 0; i < 3; i++) {
if (form.q1[i].checked === true) {
count1++;
break;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
answer1 = form.q1[i].value; //error was here .
a = Math.floor(answer1);
document.getElementById("result").innerHTML = "The selected values are " + "</br>" + answer1;
}
if it worked in google chorm that's because browsers ignore some errors.
Related
I'm trying to validate the radio buttons so that an error pops up when it's not checked.
However the error won't disappear unless I select an option from the Question 2 set and nothing from Question 1.
I'm trying to have both messages pop up for both questions if unchecked and and individually disappear when something is selected for that question
//Javascript
var answers = ["A","C"],
total = answers.length;
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpan = document.getElementById("choice_error");
var isChecked = false;
errorSpan.innerHTML = "";
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpan.innerHTML = "Please select a choice.";
}
}
return isChecked;
}
function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
document.getElementById("flag"+i).innerHTML = "";
if(getCheckedValue("choice"+i) == answers[i])
{
score += 1;
document.getElementById("flag"+i).innerHTML = "Your answer is correct.";
}
else if(getCheckedValue("choice"+i) != answers[i])
{
document.getElementById("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore()
{
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header><h1>Disney Quiz</h1></header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last"value=""><br>
<section id="radio1">
<p> Question 1) What was Walt Disney's first character he created? <span id="choice_error"></span></p>
<input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit<br>
<input type="radio" name="choice0" value="B">Donald Duck<br>
<input type="radio" name="choice0" value="C">Mickey Mouse<br>
<input type="radio" name="choice0" value="D">Goofy<br>
<p id="flag0"></p>
</section>
<section id="radio2">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span id="choice_error"></span></p></p>
<input type="radio" name="choice1" value="A">Movie<br>
<input type="radio" name="choice1" value="B">Live-Action<br>
<input type="radio" name="choice1" value="C">Cel-animated Film<br>
<input type="radio" name="choice1" value="D">Cartoon<br>
<p id="flag1"><p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer> <p align="center"> Project 4 - Fall 2018 </p> </footer>
</body>
</html>
fastest method:
HTML:
<span id="choice_error_choice0"></span>
<!-- ... -->
<span id="choice_error_choice1"></span>
JS:
function getCheckedValue(radioName)
{
let isChecked = true;
let exist = document.querySelector(`input[name='${radioName}']:checked`);
let choice_error = document.getElementById('choice_error_'+radioName);
choice_error.innerHTML = "";
if (exist == null)
{
isChecked = false;
choice_error.innerHTML = "Please select a choice.";
}
return isChecked;
}
In your code both error spans have the same ID "choice_error". No two html elements should have the same id, as then the browser won't be able to differentiate them.
If you want to access both error span elements, you can give each of them a ccs class "choice_error" and call the method document.getElementsByClassName().
Also you need to clear the error span inside the loop
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpans = document.getElementsByClassName("choise_error");
var isChecked = false;
for (var y = 0; y < radios.length; y++)
{
errorSpans[y].innerHTML= ""; // clear the span
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpans[y].innerHTML = "Please select a choice."; // error message
}
}
return isChecked;
}
I've tidied a couple of things up. Using label for a start.
The main difference is I now use a parent question id to group our answers and change to class for choice_error.
Then I've use document.querySelector to find the checked answer and set the child error messages display style.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function getAnswer(QuestionId) {
//Get the selected answer radio button
var answer = document.querySelector("#" + QuestionId + " input[type=radio]:checked");
//It there isn't one
if (answer === null) {
//show the error mesage
document.querySelector("#" + QuestionId + " .choice_error").style.display = "inline";
} else {
//Otherwise hide the message
document.querySelector("#" + QuestionId + " .choice_error").style.display = "";
//And set the answer value
answer = answer.value;
}
return answer;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
document.getElementById("flag" + i).innerHTML = "";
if (getAnswer("radio" + (i + 1)) == answers[i]) {
score += 1;
document.getElementById("flag" + i).innerHTML = "Your answer is correct.";
}
/*No need to check again, it either matches or doesn't*/
else {
document.getElementById("flag" + i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore() {
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header>
<h1>Disney Quiz</h1>
</header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</body>
</html>
We could refactor this some more, let one method handle manipulating the question related actions.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function checkAnswer(QuestionId, Answer) {
var isCorrect = false;
var questionElement = document.getElementById(QuestionId);
//Get the selected answer radio button
var answerElement = questionElement.querySelector("input[type=radio]:checked");
//It there isn't one
if (answerElement === null) {
//show the error mesage
questionElement.querySelector(".choice_error").style.display = "inline";
questionElement.querySelector("[id^=flag]").innerHTML = "";
} else {
//Otherwise hide the message
questionElement.querySelector(".choice_error").style.display = "";
//And chcek answer
isCorrect = Answer == answerElement.value;
questionElement.querySelector("[id^=flag]").innerHTML = "Your answer is " + (isCorrect ? "correct" : "incorrect");
}
return isCorrect;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
if(checkAnswer("radio" + (i + 1), answers[i])) {
score++;}
}
return score;
}
function returnScore() {
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header>
<h1>Disney Quiz</h1>
</header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</body>
</html>
I have
options.html
<html>
<head>
<meta charset="utf-8">
<title>Options</title>
<script src="js/options.js"></script>
</head>
<body>
<p>
<input type="checkbox" name="checkbox" id="checkbox">
<label for="checkbox">Test</label></p>
<p>
<label for="textfield">Filter:</label>
<input type="text" name="textfield" id="textfield">
</p>
<p>Select type:</p>
<p>
<label>
<input type="radio" name="RadioGroup1" value="True" id="RadioGroup1_0">
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="False" id="RadioGroup1_1">
Radio</label>
</p>
<p>
<button id="BtnSave">Save</button>
<button id="BtnRestore">Restore</button>
<br>
</p>
</body>
</html>
options.js
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("BtnSave").addEventListener("click", ButtonSave);
document.getElementById("BtnRestore").addEventListener("click", ButtonsRestore);
});
function ButtonSave() {
var ... = document.getElementById('...').checked;
chrome.storage.sync.set({...: ...}, function() {
});
}
function ButtonsRestore() {
chrome.storage.sync.get(likesColor, function (retVal) {
});
}
How save: CheckBox status, value in Edit and RadioGroup ItemIndex?
How restore: CheckBox (Checked := True), Edit (Text := 'bla-bla') and RadioGroup (ItemIndex := 1)?
Thanks!
The "checked" property of both checkboxes and radio buttons will let you see if they are selected:
console.log(document.getElementById(id).checked)
You can also use this to programmatically set them, e.g.
document.getElementById(id).checked = true
For text boxes, their current value is in the value property:
console.log(document.getElementById(id).value)
and likewise can be set:
document.getElementById(id).value = "whatever"
Solved
function save_options() {
var elements = document.getElementsByName('RadioGroup1');
for (i = 0; i < elements.length; i++) {
if (elements[i].checked) {
localStorage.setItem("RadioGroup1", elements[i].value);
break;
}
}
}
function restore_options() {
var elements = document.getElementsByName('RadioGroup1');
var num = localStorage.getItem("RadioGroup1");
elements[num].checked = true;
}
I'm creating a mini quiz, if the answer is correct the background will be green, if is wrong will be red
here is the code of HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="forma">
<div class="pyetja"><h3>1. The flag if Italy which color has..</h3>
<div class="formafoto"><div class="foto"></div><div class="pergjigjet"><div class="pergjigje">
<div class="pergjigjemajtas">
white and blue
</div>
<div class="pergjigjedjathtas" id="0">
<label><input type="radio" value="1" name="0" unchecked="">right</label>
<label><input type="radio" value="0" name="0" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigje">
<div class="pergjigjemajtas">
white and red
</div>
<div class="pergjigjedjathtas" id="1">
<label><input type="radio" value="1" name="1" unchecked="">right</label>
<label><input type="radio" value="0" name="1" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigjeno">
<div class="pergjigjemajtas">
white red and green
</div>
<div class="pergjigjedjathtas" id="2">
<label><input type="radio" value="1" name="2" unchecked="">right</label>
<label><input type="radio" value="0" name="2" unchecked="">wrong</label>
</div>
</div></div></div></div>
<div class="question">
<input id="buton" type="button" value="Finish!" onClick="getScore(this.form); getResult(this.form);">
<p> <strong class="bgclr">Result = </strong><strong><input class="bgclr1" type="text" size="2" name="percentage" disabled></strong><br><br>
<div id="rezultati"></div>
</div>
</form>
</body>
</html>
and javascript
// Insert number of questions
var numQues = 3;
// Insert number of choices in each question
var numChoi = 2;
// Insert number of questions displayed in answer area
var answers = new Array(2);
// Insert answers to questions
answers[0] = 1;
answers[1] = 1;
answers[2] = 1;
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
}
}
}
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
if(score > 3) {
document.getElementById("rezultati").innerHTML = "Congratulation!";
} else {
document.getElementById("rezultati").innerHTML = "Try again!";
}
form.percentage.value = score;
form.solutions.value = correctAnswers;
}
// End -->
</script>
I get always red background and if the answer is correct, maybe document.getElementByName("0").value is not getting a number to make true the condition
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
Probably your error is in this line of code, the id="0" is a div and you are trying to get the value of it, this might result into undefined and the value answer[0] is 1, thus 1 is not equal to radio1, thus it is always getting into the else block.
I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail
How to get the checked option in a group of radio inputs with JavaScript?
<html>
<head>
<script type="text/javascript">
function testR(){
var x = document.getElementsByName('r')
for(var k=0;k<x.length;k++)
if(x[k].checked){
alert('Option selected: ' + x[k].value)
}
}
</script>
</head>
<body>
<form>
<input type="radio" id="r1" name="r" value="1">Yes</input>
<input type="radio" id="r2" name="r" value="2">No</input>
<input type="radio" id="r3" name="r" value="3">Don't Know</input>
<br/>
<input type="button" name="check" value="Test" onclick="testR()"/>
</form>
</body>
</html>
http://www.somacon.com/p143.php
If you need the actual element and not just the selected value, try this:
function findSelected(){
for (i=0;i<document.formname.radioname.length;i++){
if (document.formname.radioname[i].checked){
return document.formname.radioname[i];
}
}
}
generic functions (loosely based on yours )
function getRadioGroupSelectedElement(radioGroupName) {
var radioGroup = document.getElementsByName(radioGroupName);
var radioElement = radioGroup.length - 1;
for(radioElement; radioElement >= 0; radioElement--) {
if(radioGroup[radioElement].checked){
return radioGroup[radioElement];
}
}
return false;
}
function getRadioGroupSelectedValue(radioGroupName) {
var selectedRadio = getRadioGroupSelectedElement(radioGroupName);
if (selectedRadio !== false) {
return selectedRadio.value;
}
return false;
}