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) {
Related
I am doing an assignemnt for school to showcase our knowledge of javascript. It is doing everything I want it to except when I adjust the first input from an empty string to a value it still has the display of first name required. I was also wondering if anyone had insight as to how to display the needed inputs when the other buttons I have clicked are cliked as I don't want the other functions to run unless all inputs are filled in the form. Thanks!
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t2result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t1result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
you were getting wrong element in your function validate in first condition , in else condition you were getting t2result instead of t1, hope this will work now.
I created a Chicago employee search index and wanted to create an alert when there are no matching records found, but can't seem to be able to find out what value I need to put in for when it's empty. Ideally, when the function get's submitted and no results are found, it would push an alert onto the screen indicating no matching records found.
The alert right now is located in the submit function in the last bit of code posted
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
})
}
<!doctype html>
<html>
<head>
<title>Salary Info Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="ChicagoEmployees.js"></script>
<script src="demoLS.js"></script>
</head>
<body>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>
</body>
</html>
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
if (searchKey.isEmpty()) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
If I understand your question correctly, you can check if there's any matching data at the end of the getlist()
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
// ... codes ...
callBack(results);
// like this
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>
Good morning,
I've got some javascript to check if inputs are empty before printing and if so, cancel the print.
I have added jquery datepicker to one of the fields as a class and now it only applies one class or the other. (I have tried the datepicker as an ID instead) but doesn't work.
Javascript:
function checkForm(thisForm) {
var len = thisForm.elements.length ;
var cnt = 0 ;
for ( var i=0; i < len; i++) {
var elem = thisForm.elements[i] ;
if (elem.className == "formFieldRequired") {
if ((elem.value == "" || elem.value == -1)) {
alert("WARNING:\n You must supply information for the " + elem.name + " field");
elem.focus();
return false;
}
}
}
window.print();return true;
}
Input:
<input name="Effective Date" type="text" style="width:12%;" class="formFieldRequired datepicker" placeholder="DD/MM/YYYY" onkeyup="javascript:return mask(this.value,this,'2,5','/');" maxlength="10">
Any ideas on why this is happening and any fixes? - I may be missing something completely obvious!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/jquery.datetimepicker.js"></script>
<form id="myform">
<input name="Effective Date" type="text" style="width:12%;" class="formFieldRequired datepicker" placeholder="DD/MM/YYYY" onkeyup="javascript:return mask(this.value,this,'2,5','/');" maxlength="10">
</form>
<script>
function checkForm(thisForm) {
var len = thisForm.elements.length;
var cnt = 0 ;
for ( var i=0; i < len; i++) {
var elem = thisForm.elements[i] ;
console.log(elem.className)
if (elem.className.indexOf("formFieldRequired") != -1) {
if ((elem.value == "" || elem.value == -1)) {
alert("WARNING:\n You must supply information for the " + elem.name + " field");
elem.focus();
return false;
}
}
}
window.print();return true;
}
checkForm(document.getElementById("myform"));
</script>
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
}
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.