Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I added the alert to test if the script was working at all, once i deleted the function it did, but once I add the function the html doesn't even show the alert. I tried loading the code in a different file and calling it in the head, the body, for some reason the code won't even load much less can i get the button at the end to work.
<!DOCTYPE html>
<html>
<head>
<title> Astronomy Quiz </title>
</head>
<body>
<div>
<script>
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
</script>
<center>
<h1> Astronomy Quiz </h1>
</center>
<h3> True / False </h3>
<form id = "quiz">
<label><b>1)</b> According to Kepler the orbit of the earth is a circle with
the sun at the center.
<input type = "radio" name = "q1" value = "True" />
True
<input type = "radio" name = "q1" value = "False" />
False</label>
<br>
<br>
<label><b>2)</b> Ancient astronomers did consider the heliocentric model of
the solar system but rejected it because they could not detect parallax.
<input type = "radio" name = "q2" value = "True" />
True
<input type = "radio" name = "q2" value = "True" />
False</label>
<br>
<h3> Multiple Choice </h3>
<b>3)</b> The total amount of energy that a star emits is directly related
to its
<br>
<input type = "checkbox" name = "q3" value = "a" />
a) surface gravity and magnetic field
<br>
<input type = "checkbox" name = "q3" value = "b" />
b) radius and temperature
<br>
<input type = "checkbox" name = "q3" value = "c" />
c) pressure and volume
<br>
<input type = "checkbox" name = "q3" value = "d" />
d) location and velocity
<br>
<br>
<b>4)</b> Stars that live the longest have
<br>
<input type = "checkbox" name = "q4" value = "a" />
a) high mass
<br>
<input type = "checkbox" name = "q4" value = "b" />
b) high temperature
<br>
<input type = "checkbox" name = "q4" value = "c" />
c) lots of hydrogen
<br>
<input type = "checkbox" name = "q4" value = "d" />
d) small mass
<br>
<h3> Fill in the Blank </h3>
<label><b>5)</b> A collection of a hundred billion stars, gas, and dust is
called a
<input type = "text" name = "q5" value = "" size = "15" />
.</label>
<br>
<br>
<label><b>6)</b> The inverse of the Hubble's constant is a measure of the
<input type = "text" name = "q6" value = "" size = "15" />
of the universe.</label>
<br>
<br />
<input type = "button" value = "Grade" onclick = "quiz()" />
<input type = "reset" name = "Clear" value = "Clear" />
</form>
</div>
</body>
</html>
Try this out:- http://jsfiddle.net/adiioo7/fDDCW/
JS:-
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
on line 88:
if(get.q6.value.match(/^age$/i))
you missed ) in your javascript...
You have missed a ) here:
if(get.q6.value.match(/^age$/i)
Change this to:
if(get.q6.value.match(/^age$/i))
if (get.q6.value.match(/^age$/i) {
This like is missing a closing )
Try this:
if (get.q6.value.match(/^age$/i)) {
To find what's wrong with your JavaScript code use try-catch as follows-
<script>
try
{
/*some JS code*/
}
catch(foo)//Use any variable in place of foo
{
alert(foo);
}
</script>
This will definitely not correct the error but may help you much to find what the error is. Though this is not an answer but you may follow this approach globally anywhere anytime.
Related
I have a program that is suppose to ask the user for their ID, First Name, Last Name, select a Rank (grade level), and the GPA. After all fields go through error checking, the data should then be put into an object called student. Next the student object should be pushed to the Summary Array. Displaying the first and last name, next line ID, next line Class Rank, next line GPA.
UPDATE CURRENTLY: all error checking (if/elses) works! Secondly, only the "--------" happens when Add Student is pressed besides the error checking.
Full Code:
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
studentID = document.getElementById('Text1').value;
studentFirst = document.getElementById('Text2').value;
studentLast = document.getElementById('Text3').value;
Rank = document.getElementById('Select1').value;
studentGPA = document.getElementById('Text4').value;
if (!studentList.includes(studentID)) {
if (studentID != '') {
if (studentFirst != '') {
if (studentLast != '') {
if (Rank != -1) {
if (studentGPA != '') {
if (studentGPA > 0 && studentGPA < 4) {
var Student = {
studentID: document.getElementById('Text1').value,
studentFirst: document.getElementById('Text2').value,
studentLast: document.getElementById('Text3').value,
Rank: document.getElementById('Select1').value,
studentGPA: document.getElementById('Text4').value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>"
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option value="-1">(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
You need to initialize Summary to an empty array. Otherwise, Summary.push() gets an error because you can't push onto undefined.
The index of the prompt option in the Rank menu is 0, not 1, so you should check for that in the validation.
The Create() function reassigns all the variables that contain the input elements, replacing them with their values. You should use different variables, or just use the .value properties of the global variables.
You need to convert the value of Rank to a number before comparing with numbers.
You're missing a + at the end of the first line of the string you're appending to the DIV, so you're only adding the ---- line.
When checking for duplicates, you need to compare studentID.value with the studentID property of the array element, not the whole array element. And you should be searching Summary, not studentList.
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
if (!Summary.find(s => s.studentID == studentID.value)) {
if (studentID.value != '') {
if (studentFirst.value != '') {
if (studentLast.value != '') {
if (Rank.selectedIndex != 0) {
if (studentGPA.value != '') {
let GPAVal = parseFloat(studentGPA.value);
if (GPAVal > 0 && GPAVal < 4) {
var Student = {
studentID: studentID.value,
studentFirst: studentFirst.value,
studentLast: studentLast.value,
Rank: Rank.value,
studentGPA: studentGPA.value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>" +
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option>(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
Rank has no selectedIndex because Rank is not an element or node.
Rank = document.getElementById('Select1').value;
You should set the value attribute on your option tags.
<option value="-1">(Select a Rank)</option>
if (Rank != -1) {
How do I get the scoring system to work right?
It adds +1 if it's correct, but + an even bigger number if it's wrong...I just want it to add +1 to both.
It should post only +1 for wrong...
HTML
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question1' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question2' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question3' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question4' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question5' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question6' id='question6'>
</h5>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question7' id='question7'>
</div>
<button id='button' type='button' onclick='answer()'>Do you even anime?</button>
</form>
<span class='correct'>
<label for='score'>CORRECT</label>
<input type='text' id='score'>
</span>
<span class='wrong'>
<label for='wrong'>WRONG</label>
<input type='text' id='wrong'>
</span>
JavaScript:
var quizArray = [
{ answer: 'ashente' },
{ answer: 'green' },
{ answer: 'yes' },
{ answer: 'love' },
{ answer: 'both' },
{ answer: 'chopper' },
{ answer: 'heavens' }
]
function answer() {
var correct = 0;
var wrong = 0;
for (i = 0; i < quizArray.length; i++) {
var question1 = document.getElementById('question1').value;
if (question1 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question3 = document.getElementById('question3').value;
for (i = 0; i < quizArray.length; i++) {
if (question3 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question4 = document.getElementById('question4').value;
for (i = 0; i < quizArray.length; i++) {
if (question4 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question5 = document.getElementById('question5').value;
for (i = 0; i < quizArray.length; i++) {
if (question5 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question6 = document.getElementById('question6').value;
for (i = 0; i < quizArray.length; i++) {
if (question6 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question7 = document.getElementById('question7').value;
for (i = 0; i < quizArray.length; i++) {
if (question7 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
Here it is. You have several problems. Check teh code and feel free to ask anything:
var quizArray = [{
answer: 'ashente'
}, {
answer: 'green'
}, {
answer: 'yes'
}, {
answer: 'love'
}, {
answer: 'both'
}, {
answer: 'chopper'
}, {
answer: 'heavens'
}]
function answer() {
var correct = 0;
var wrong = 0;
var questions = document.querySelectorAll(".question");
for (i = 0; i < quizArray.length; i++) {
if (questions[i].value.toLowerCase() == quizArray[i].answer.toLowerCase()) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
(function(){
document.getElementById("button").addEventListener("click", answer);
})();
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question' id='question6'>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question' id='question7'>
</div>
<input id='button' type='submit' value="Do you even anime?">
<span class='correct'><label for='score'>CORRECT</label><input type='text' id='score'></span>
<span class='wrong'><label for='wrong'>WRONG</label><input type='text' id='wrong'></span>
I will calrify some points anyway. As you could see, the main difference is the size of the js. You had teh same piece of code for each question, when you are in a situation like this, you should use a function or a loop. This is part of the DRY concept. So taking all the questions in an array and iterate over them is easier than create a piece of code for each one.
I added the function toLowerCase because is annoying failing answers only if you missed that detail. Using this function is not necessary, it's up to you.
In the HTML part I must remark that if you have a button that sends a form you should create an input which type is submit. HTML button is not properly for submitting a form. It can do the job, but it is not the correct way.
You use inputs to show the score, but, instead it will be better to use plain text. Again, it's not bad but it's handier.
The issue is related to how the incrementing is implemented in the for-loops. Let's take the first loop as an example:
You are trying to assess whether or not question 1 has been answered correctly by comparing the users answer with every possible answer in the quizArray element. With 7 questions we should have 7 iterations of the loop. In each iteration, you check if the answer for question 1 is correct and increment the correct variable accordingly. Otherwise you increment the wrong variable. So for 7 iterations of the for-loop you are incrementing the wrong variable at least 6 times.
Instead of trying to increment the correct and wrong variables in each iteration, you can use a flag to determine if the question was answered correctly, and then increment the variables after the loop. For example:
var correct = 0;
var wrong = 0;
var question1 = document.getElementById('question1').value;
var answerCorrect = false;
for (i = 0; i < quizArray.length; i++) {
if (question1 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
answerCorrect = false;
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
I have created a conversion table which converts miles to kilometres and kilometres to miles depending on whichever one the user chooses. They input two numbers which indicates the two ranges so if they input 2 and 5 and choose km to m it will then show 2km to 5km converted to miles. However, what I am trying to do is if the user inputs a greater number to start with for instance if you enter 10 and 2 it should still do the same but rather it should go from 10km down to 2km so in descending order, so I know it will be something along the lines of if(rangeStart>rangeEnd){i--;}
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function conversion(n) {
if (document.getElementById('mtokm').checked) {
return (n/0.62137).toFixed(2);
}
else {
return (n*0.62137).toFixed(2);
}
}
function conversionTable(rangeStart, rangeEnd) {
if(atLeastOneRadio() && rangeStart != false && rangeEnd != false) {
divStr="<table border=1><tr><td>Miles</td><td>Kilometres</td></tr>";}
for(i=rangeStart;i<=rangeEnd;i++) {
if(i%2==0)
{
divStr+= "<tr bgcolor=\"yellow\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
else
{
divStr+= "<tr bgcolor=\"green\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
}
document.getElementById("divResult").innerHTML=divStr;
}
else
{
alert("Please make sure you have entered an integer in both text boxes");
}
}
function getnputValue(input) {
var nn = $("input[name=convert]:checked").val()
var myInt = document.getElementById(input).value;
if(myInt == parseInt(myInt))
return parseInt(myInt);
else
return false;
}
function check() {
var radios = document.getElementsByName("choice");
$("input[name=convert]:checked").val()
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
return true;
}
}
return false;
}
function atLeastOneRadio() {
return ($('input[type=radio]:checked').length > 0);
}
</script>
</head>
<body>
<p>
Start : <input type=textbox id=rangeTxt value=""/>
End : <input type=textbox id=rangeTxt2 value=""/>
<input type=radio name="convert" id="mtokm" value ="Miles to Kilometre"/> Miles to Kilometre
<input type=radio name="convert" id="kmtom" value ="Kilometre to Miles"/> Kilometre to Miles
<br>
<br>
<button onClick="conversionTable(getnputValue('rangeTxt'), getnputValue('rangeTxt2'))">Convert</button>
</p>
<div id="divResult">
</div>
</body>
</html>
Check whether the end is higher or lower than the start. Then set variables that are used to control the for loop.
var increment, compare;
if (rangeStart <= rangeEnd) {
increment = 1;
compare = function(x, y) {
return x <= y;
};
} else {
increment = -1;
compare = function(x, y) {
return x >= y;
};
}
for (i = rangeStart; compare(i, rangeEnd); i += increment) {
// display code
}
This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Closed 7 years ago.
I am trying to make a factorial calculator. How can I check if the input is empty or not? I tried 'null'. But it didn't work or I couldn't use it properly.
sorry for the stupid question. I am newbie in JavaScript
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if( !(isNaN(input))) {
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else if (input == null){
return "Please input a number"
}
else{
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function() {
if (input.trim() == '') {
return "Please input a number"
} else if (!(isNaN(input))) {
var result = 1;
for (var i = 1; i <= input; i++) {
result = result * i
}
return result;
}
}
document.getElementById("input2").value = ever();
}
<p>Input:
<input type="text" id="input1" />
</p>
<p>Input:
<input type="text" id="input2" />
</p>
<button onclick="myFriday()">Calculate</button>
<p>RESULT: <span id="result" style="color:red"></span>
</p>
is that what you looking for?
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if(input.match(/\D/) == null){ // changes made here
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else{ // one else is enough
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
When you use .value you get a string value in return.
This means that when you enter nothing in the input it'll return ""
So you should change this piece of code
input == null
Into this
input === ""
Note that I also wrote === instead of ==
Using === in javascript is faster than == when the objects are of the same type.
Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}