Trouble with Loop and Functions in Javascript - javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );

It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

Related

Comparision between 2 Object

I am working on a course registration system.I need to check for time conflicts.
Already registered courses object:
{"00001":{"days":"Monday-Tuesday","hours":"11:40-12:30*13:40-15:30"}}
this means that 00001 course is in monday 11:40-12:30 in tuesday 13:40-15:30
Courses to register object:
{"00003":{"days":"Friday","hours":"9:40-10:40"}}
I have managed to check is student already registered to course with this code:
Object.keys(registeredcoursesobject).forEach(function(key){
if( Object.keys(coursestoregisterobject).includes(key)) {
alert("You have already registered to "+key+" crn number course");
//return;
}
});
A course can be at most 2 days in a week and in 1 different time intervals(what if 2 time intervals??) which means that there will be only one "-" in days property and only one "*" in hours property.
I am new to programming and working on this for days any ideas ?
I hope this answer is still relevant for you. Here is what I have:
var registeredcoursesobject = {"00001":{"days":"Monday-Thursday","hours":"11:40-12:30*16:30-18:30"}}
var coursestoregisterobject = {"00002":{"days":"Monday-Friday","hours":"10:40-15:30*16:40-18:00"}}
var getTicks = function(timeStr) {
return new Date('1970-01-01T' + timeStr + ':00Z').getTime();
}
Object.keys(registeredcoursesobject).forEach(function(rKey){
if( Object.keys(coursestoregisterobject).includes(rKey)) {
alert("You have already registered to "+rKey+" crn number course");
return false;
};
Object.keys(coursestoregisterobject).forEach(function(cKey){
var regDays = registeredcoursesobject[rKey].days.split('-');
var regHours = registeredcoursesobject[rKey].hours.split('*');
var courseDays = coursestoregisterobject[cKey].days.split('-');
var courseHours = coursestoregisterobject[cKey].hours.split('*');
regDays.forEach(function(rDay, i) {
var rHourRange = regHours[i];
// I assume you need to check there is same date/time pain in registeredcoursesobject and coursestoregisterobject
courseDays.forEach(function(cDay, j) {
if (rDay == cDay) {
var cHourRange = courseHours[j];
// now, do you need to compare hours be equal exactly or do you need to check time overlap?
// assume you just need to ckeck hour ranges are equal, then:
if (rHourRange == cHourRange){
// means equal
alert("You have already registered to "+cKey+" crn number course on day "+cDay+" at "+cHourRange+" hours.");
return true;
}
// if you need to check range overlap
var rTime = rHourRange.split('-');
rTimeRange = [getTicks(rTime[0]), getTicks(rTime[1])];
rStartT = Math.min.apply(null, rTimeRange), rEndT = Math.max.apply(null, rTimeRange);
var cTime = cHourRange.split('-');
cTimeRange = [getTicks(cTime[0]), getTicks(cTime[1])]
cStartT = Math.min.apply(null, cTimeRange), cEndT = Math.max.apply(null, cTimeRange);
// now your rangeTime is a pair of int values, that represent time range rStartT:rEndT
// and your courseTime is a pair of int values cStartT:cEndT
// so now you just check the overlap of two integer pais.
// according to this: https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap#answer-3269471
if (rStartT < cEndT && cStartT < rEndT) {
alert("You have already registered to "+cKey+" crn number course on day "+cDay+" within time range "+cHourRange+" hours overlap with "+rHourRange+" time range.");
// means time ranges are overlap at some range. But I don't count the border, like "14:00-15:00" and "15:00-16:00" do not overlap
// otherwise replace < with <=
return true;
}
}
})
});
return false;
});
});
I am making some assumptions here about your task.
UPDATE: added time range check.
UPDATE: check keys equal first and values swap if start time is for some reason is bigger than end time.

Create a web page with prompts

My prompt boxes aren't working? Ever since I've put in the element stuff there not working.
I need prompt boxes so I can enter info and then that info to automatically go into a table and then it to automatically read the largest amount of $ by having a * in the row of the table. I'm not 100% on js coding so don't laugh if its a simple fix (it's the simple things that get me).
This is my code, I don't know what I've done wrong
"my table is in the head"
function money(){
this.currency = "";
this.amount = "";
this.exchangeRate = "";
this.ausDollars = "";
tbody = document.getElementsByTagName('tbody')[0];
for (var i = 0; i <= 3; i++)
trElement = document.createElement('tr');
tbody.appendChild(trElement);
// Read the 3 letter currency abbreviation entered
currency = prompt('Please enter a 3-letter currency abbreviation', +i, "");
// If the input data is invalid ask the user to re-enter it
while (currency.length != 3) {
currency = prompt('Currency abbreviation was not entered', "");
currency = parseFloat(currency);
}
currencyTH = document.createElement('th');
currencyText = document.createTextNode(currency);
currencyTH.appendChild(currencyText);
trElement.appendChild(currencyTH);
// Read the amount and convert it to entered currency
amount = prompt('Please enter an amount of money in that currency', +i, "");
// If the input data is invalid ask the user to re-enter it
while (isNaN(amount) || amount < 0) {
amount = prompt('An amount of money was not entered')
amount = parseFloat(amount);
}
amountTH = document.createElement('th');
amountText = document.createTextNode(amount);
amountTH.appendChild(amountText);
trElement.appendChild(amountTH);
exchangeRateTH = document.createElement('th');
exchangeRateText = document.createTextNode(exchangeRate);
exchangeRateTH.appendChild(exchangeRateText);
trElement.appendChild(exchangeRateTH);
}
The problem is that you are using prompt() to both prompt the user for input and display error messages in relation to user input. For that, you're looking for alert().
First you set the currency in a prompt with:
currency = prompt('Please enter a 3-letter currency abbreviation', +i, "");
Then you run:
currency = prompt('Currency abbreviation was not entered', "");
This overwrites the value that was initially stored in currency, so you are unable to run parseFloat() on it on the next line:
currency = parseFloat(currency);
To resolve this, use:
alert('Currency abbreviation was not entered');
Note that this is the same case for amount. Instead of:
amount = prompt('An amount of money was not entered');
Use:
alert('An amount of money was not entered');
Also note that your while loop structure is slightly wrong for indefinitely prompting until a correct value is met. Instead of initially prompting and then running your while loop, you should set a variable outside of the loop and then check the condition. And the parseFloat() must come outside of the while loop, or else you'll get stuck in an indefinite loop!
var currency = '';
currency = prompt("Please enter 3 characters");
while (currency.length != 3) {
alert('Currency must be three characters');
currency = prompt("Please enter 3 characters");
}
currency = parseFloat(currency);
console.log("The stored value was: " + currency);
Hope this helps! :)

JavaScript For Loop with user entry error

I am currently dabbling with JavaScript and am doing some simple calculations using for loops and I am attempting to take user info for the Table set they want and the numbers they wish to multiply between e.g.
Enter Table set: 12
Enter where to start multiplying from: 3
Enter how high to multiply: 6
This would print:
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
My issue is that when I ask the user to select how high they wish to multiply to, if they select a number greater than 9 it doesn't enter the for loop and prints nothing yet 9 and below works.
This is the simple enough code:
function UserEnteredTables()
{
var tableNumber = prompt("Please enter the number tables to use: ");
var numberLowerLimit = prompt("Please select where you want to start multiplying from: ");
var numberUpperLimit = prompt("Please select how high to multiply to: ");
document.write("Before the loop " + numberUpperLimit + "<br/>");
for (i = numberLowerLimit; i <= numberUpperLimit; i++)
{
document.write("Made it inside the loop " + "<br/>");
document.write(tableNumber + " * " + i + " = " + (i * tableNumber) + "<br/>");
}
document.write("After the loop " + numberUpperLimit);
}
Apologies for any indentation issues, had issues pasting for some reason
I have attached two images, one where I enter the upper limit to 9 and then one were I enter 10. As you can see the 10 doesn't enter the loop.
I assume that I have missed something very simple but I would appreciate if someone could explain what the issue is or if its something to do with JavaScript loops.
If there is something wrong with the post or you require some other code to fully understand just let me know.
Thanks in advance :)
The issue is with the prompt value returned: its typeof is string, while what you want is number for the loop to work correctly.
Use parse() to extract the numeric value out of the prompt value, see here:
https://jsfiddle.net/jwvj2aab/1/
Note that you will need to handle user input in order to deny anything but numbers

Javascript assignment for school involving objects and Validation not working correctly

the past two days I've been really struggling on finishing this assignment.
The assignment goal is to create a javascript that takes in Student information until the user either hits cancel or enters in blank text.
the information gets validated every time the user enters information if it is valid, it is then saved to a Student Object Array.
Here is my code:
var Student =[];
// Validates Student Courses, loops through making sure they are equal to courseList values.
function validateCourses(courses){
var valid='';
var courseList = ['APC100','IPC144','ULI101','IOS110','EAC150','IBC233','OOP244','DBS201','INT222'];
alert(courses);
for(var i =0;i<courseList.length;i++){
var a = courses;
a.splice();
if(a[i]!==courseList[i]){
valid=false;
}
else{
valid=true;
}
}
return valid;
}
function formatingName(name){
var res ='',cap='';
res = res + name.charAt(0).toUpperCase();
cap = res + name.substr(1);
return cap;
}
// I'm having issues with this validation for the student id. the student id can only be xxx.xxx.xxx
function validateStudentID(sid){
var validate=0;
var patt1 = /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/;
var result = patt1.test(sid);
return result;
}
var courseSelect=[];
var tag=0;
// this displays what users are in what course depending on what the user enters
function code(coursecode){
for(var w = 0;w<count;w++){
for(var t = 0;t<Student[w].courses.length;t++){
var a = Student[w].courses;
a.splice();
if(a[t] == coursecode){
tag=1;
}
}
if(tag){
courseSelect.push(Student[w].fname + " " + Student[w].lname + " " + Student[w].id + " " + Student[w].email);
}
}
alert('List students registered in ' + coursecode + ' :\n\n' + courseSelect.join('\n'));
}
// main functions and validation calls
var userInput = "";
var i=0,count=0,j=4,flag=false;
var result='',courses=[];
var Student,validCourses;
do{
userInput = prompt("Please enter first name, last name,student ID,\n" +
"email and courses (speareted by ',').");
if(userInput != null && userInput !=''){
result = userInput.split(',');
for(var i=4;i<result.length && i < 10;i++){
courses.push(result[i].toUpperCase());
}
// VALIDATION OF STUDENT ID AND STUDENT COURSES */
while(!flag){
var valid = validateStudentID(result[2]);
alert(valid);
if(valid){
id = result[2];
flag=true;
}
else {
alert(Student.id + " is not valid Student ID!" + "\n" + "Please try again.");
flag=false;
}
validCourse = validateCourses(courses);
if(validCourse){
flag=true;
}
else {
alert( validCourse + " is not the course provided by the CPD program! \n Please try again");
flag=false;
}
}
if(flag){
Student.push({
fname:formatingName(result[0]),
lname:formatingName(result[1]),
id:result[2],
email:result[3].toLowerCase(),
courses:courses,
});
count++;
i++;
}
else {
Student = [];
}
}
}while(userInput != null && userInput !='');
alert('There are total '+ count + ' students registered');
var coursecode = prompt("Please enter course code: ");
code(coursecode);
Some of the most obvious problems in your code are:
You have a while(!flag) loop after the input section. That loop contains no other request to input anything. Therefore it will run endlessly if your validate* methods return false.
Your regular expression /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/ isn't doing what you want it to do. You can simplify it to just /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}$/ as all you want to know is whether your input parameter sid contains three number blocks, each of length 3. You don't need any braces for that and escaping them via \(? would anyways be wrong. You also didn't escape your points via \., which is wrong as they would match basically any character. You should read up more about regular expressions.
Your loop in validateCourses looks wrong. Why do you assign courses to a new variable (it isn't copied to a) and then call splice()? Your following if condition is also wrong, as it assumes that a and courseList have equal length and that the positions of the courses would match. That's certainly not what you want. You should check for each course in course whether it is contained in courseList, e.g.: var notInCourseList = courses.filter(function(course) { return (courseList.indexOf(course) == -1); }); and then return (notInCourseList.length == 0);. A forEach loop would be an easy alternative. You should read some tutorials about that.
Similarly, I don't see any good reason for var a = Student[w].courses; a.splice(); in code(). Just check directly on Student[w].courses.
Slightly more working jsfiddle here.

Adding function is disabling other functions in the js file

I had this function in a js file and everything was working just fine :
function check_acco_form()
{
var name=$("#name").val();
var institution=$("#institution").val();
var year=$("#year").val();
//PNR Data
var pnr1=$("#pnr1").val();
var pnr2=$("#pnr2").val();
// Arrival date info
var arr_year=$("#arr_year").val();
var arr_month=$("#arr_month").val();
var arr_date=$("#arr_date").val();
//Departure date info
var dep_year=$("#dep_year").val();
var dep_month=$("#dep_month").val();
var dep_date=$("#dep_date").val();
var numericExpression = /^[0-9]+$/;
//Name, institution and year must not be empty
if(name=="" || institution=="" || year=="")
{
alert("One or more fields are empty.");
return;
}
//PNR must be all numbers
if(!pnr1.match(numericExpression) || !pnr2.match(numericExpression))
{
alert("A PNR number consists of 10 digits only. Please enter again.");
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if(pnr1.length!=3 || pnr2.length!=7)
{
alert('Invalid PNR Number.');
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if((arr_month==dep_month && dep_date<arr_date) || (dep_month<arr_month))
{
alert('Invalid dates.Please check again.');
return;
}
//Test passed. Store in database;
URL="saveAcco.php";
parameters="name="+name+"&ins="+institution+"&year="+year+"&pnr="+pnr1+""+pnr2+"&dateArr="+arr_year+"-"+arr_month+"-"+arr_date+"&dateDep="+dep_year+"-"+dep_month+"-"+dep_date;
$.get(URL+"?"+parameters,function(data){
$("#msg_box").html(data);
if(data=="Your changes have been saved." || data=="Your data has been saved and is pending approval.")
{
$("#acco_status").html('<br/><b>Accomodation Approval Status</b> : <span style="padding:3px;background-color:#f4fb3c">Approval Pending</span><br/><br/>');
}
$("#msg_box").fadeIn("slow",function(){
setTimeout('fadeOutMsgBox();',3000);
});
});
}
I made a little changes to this function (added the variables 'mobile_num' and 'train_num', included 'if' conditions to make sure the user enters numbers only and made changes to the jQuery get function) that which resulted in the following code:
function check_acco_form()
{
//Personal Information
var name=$("#name").val();
var institution=$("#institution").val();
var year=$("#year").val();
//Contact Information
var mobile_num=$("#mobile").val();
//PNR Data
var pnr1=$("#pnr1").val();
var pnr2=$("#pnr2").val();
//Train Number
var train_num=$("#trainnum").val();
// Arrival date info
var arr_year=$("#arr_year").val();
var arr_month=$("#arr_month").val();
var arr_date=$("#arr_date").val();
//Departure date info
var dep_year=$("#dep_year").val();
var dep_month=$("#dep_month").val();
var dep_date=$("#dep_date").val();
var numericExpression = /^[0-9]+$/;
//Name, institution and year must not be empty.
if(name=="" || institution=="" || year=="")
{
alert("One or more fields are empty.");
return;
}
//PNR can be empty but if entered must be all numbers
if(pnr1!="" and pnr2!="")
{
if(!pnr1.match(numericExpression) || !pnr2.match(numericExpression))
{
alert("A PNR number consists of 10 digits only. Please enter again.");
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if(pnr1.length!=3 || pnr2.length!=7)
{
alert('Invalid PNR Number.');
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
}
//Train number can be empty but if entered must be all numbers
if(train_num!="")
{
if(!train_num.match(numericExpression))
{
alert("Train number must consits of digits only");
$("#trainnum").val("");
return;
}
}
//Mobile num can be empty but must be all numbers
if(mobile_num!="")
{
if(!mobile_num.match(numericExpression))
{
alert("Invalid mobile number");
$("#mobile_num").val("");
return;
}
if(mobile_num.length!=10)
{
alert('A mobile number consists of 10 digits.Please enter again.');
return;
}
}
if((arr_month==dep_month && dep_date<arr_date) || (dep_month<arr_month))
{
alert('Departure date cannot be before arrival date.Please check again.');
return;
}
//Test passed. Store in database;
URL="saveAcco.php";
parameters="name="+name+"&ins="+institution+"&year="+year+"&pnr="+pnr1+""+pnr2+"&dateArr="+arr_year+"-"+arr_month+"-"+arr_date+"&dateDep="+dep_year+"-"+dep_month+"-"+dep_date+"&mobile="+mobile_num+"&train_num="+train_num;
$.get(URL+"?"+parameters,function(data){
$("#msg_box").html(data);
if(data=="Your changes have been saved." || data=="Your data has been saved and is pending approval.")
{
$("#acco_status").html('<br/><b>Accomodation Approval Status</b> : <span style="padding:3px;background-color:#f4fb3c">Approval Pending</span><br/><br/>');
$("#acco_letter_print").html('Download accomodation letter here');
$("#acco_letter_print").fadeIn();
}
$("#msg_box").fadeIn("slow",function(){
setTimeout('fadeOutMsgBox();',3000);
});
}); //End of get function
}
After the changes, suddenly all functions in the js file of this function have stopped working including this function. On searching the forum , I found this discussion : JavaScript function causing all other functions not to work inside js file which says that the error may be due to use of reserved words. However , I can't find any reserved words used as variables in my code. Any ideas what may the problem?
You have this in there:
if(pnr1!="" and pnr2!="")
It should be:
if(pnr1!="" && pnr2!="")
Any syntactical errors like this will cause the entire thing to fail, be sure to check your error console for things like this, they'll quickly point out the cause.
As an aside, try not to pass a string to setTimeout() as well, pass the function reference directly, changing this:
setTimeout('fadeOutMsgBox();',3000);
To this:
setTimeout(fadeOutMsgBox,3000);
This will give less issues, and allow the function to be anywhere in scope, it doesn't have to be global (like it would with a string).

Categories

Resources