validate input field before submitting form - javascript

I want to validate the input field 'putime' in the form because even if the 'putime' input box is empty the result is calculated and nightSurcharges is also added to the cost. So I want to validate 'putime' when it is empty otherwise the script is useless.
function TaxiFare() {
// calculates taxi fare based upon miles travelled
// and the hour of the day in military time (0-23).
var baseFare = 14;
var costPerMile = 7.00;
var nightSurcharge = 20.50; // 9pm to 6am, every night //its flat 20.50 and not per mile
var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert ("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}
var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime < 0) || (pickupTime > 23) || (pickupTime==null)) { // note the hours are 0-23. There is no 24 hour, midnight is 0 hours
alert ("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}
var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 21 || pickupTime < 6) {
cost += nightSurcharge;
}
document.getElementById("result").innerHTML = "Your taxi fare is: $. " + cost.toFixed(2);
}
And here is the Form from HTML
<form>
Miles for Journey <input type="text" id = "miles" required><br>
Pickup Time <input type = text id = "putime" required><br><br>
<input type="button" value="Calculate Fare" onclick="TaxiFare()">
<input type="reset" value="Clear"><br><br>
<span id = "result"></span>
</form>
I've tried a lot but to no avail....any help is welcomed. Thanks in advance!

how about adding an event handler to the form, in the likes of document.forms[0].submit = validateFunction;
where validateFunction might look like this:
function validateFunction()
{
var allIns = this.getElementsByTagName('input');
if(allIns.namedItem('putime').value == '')
{
alert('silly');
return false;
}
//and other checks go here, too
}

Related

How can I display addition operation? [duplicate]

I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}

How to fix infinite while loop and create functions

I am trying to make a paycheck program, that utilizes functions and while loops.
In this program, I have to create two functions, one for validating the pay rate and hours, and then one for the calculations.
In addition, I have to have the first function pass the hours and pay rate to the calculation function, and then pass it back to the first function. When I try to run the program with the first function, it seems that if I enter a pay amount under 7.25, it enters an infinite loop.
Here is the code
<script>
function payValidate(x)
{
if(isNaN(payRate) || payRate < 7.25 || payRate > 20)
{
return false;
}
else
{
return true;
}
}
function hoursValidate(x)
{
if(isNaN(hours) || hours < 1 || hours > 60)
{
return false;
}
else
{
return true;
}
}
var grossPay;
var withHolding;
var netPay;
var message;
var payRate = parseInt(prompt("Enter pay rate"));
var payRateOK = payValidate(payRate);
while(!payRateOK)
{
payRate = parseInt(prompt("Invalid pay rate. Enter pay rate again"));
payRateOk = payValidate(payRate);
}
var hours = parseFloat(prompt("Enter hours worked"));
var hoursOK = hoursValidate(hours);
while(!hoursOK)
{
hours = parseFloat(prompt("Invalid hours. Enter hours again"));
hoursOK = hoursValidate(hours);
}
grossPay = payRate * hours;
if(grossPay <= 300)
{
withHolding = grossPay * 0.10;
}
else
{
withHolding = grossPay * 0.12;
}
netPay = grossPay - withHolding;
var message = "Pay Rate: $" + payRate.toFixed(2) +
"\nHours Worked: " + hours +
"\nGross Pay $" + grossPay.toFixed(2) +
"\nWithholding $" + withHolding.toFixed(2) +
"\nNet Pay $" + netPay.toFixed(2);
alert(message);
</script>
You're creating a new variable payRateOk (notice the lower case k) instead of writing to payRateOK, the variable you check in the while loop. So payRateOK will never change, and the loop will execute infinitely.
var payRateOK = payValidate(payRate); // In here you have used "payRateOK"
while(!payRateOK)
{
payRate = parseInt(prompt("Invalid pay rate. Enter pay rate again"));
payRateOk = payValidate(payRate); // In here you have used "payRateok"
}
payRateOK != payRateOk there for you have to use same name for that
other thing is payRate is a float variable. you should use var payRate = parseFloat instead of var payRate = parseInt.
you have used hours as int type there for var hours = parseFloat should be var hours = parseInt

Using AND/OR in Javascript IF Statements

I am trying to make an IF statement in Javascript with the the following code:
<input class="entry" id="modalod" type="text" placeholder="Enter online ID" name="id" required>
<input class="entry" id="pass1" type="password" placeholder="Enter Passcode" name="psw" required>
<input class="entry" id="pass2" type="password" placeholder="Repeat Passcode" name="psw-repeat" required>
<input class="entry" id ="emailtext" type="text" placeholder="Enter Email" name="email" required>
<a href="#" class="loginbtnanchor btn btn-primary btn-md"
onclick="listids()">Login <i class="fa fa-sign-in"></i></a>
var modalok = document.getElementById("modalok");
var idarray = [];
var passcodearray = [];
var emailtextarray = [];
var od = document.getElementById("modalod").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var emailtext = document.getElementById("emailtext").value;
var at = emailtext.indexOf("#");
var period = emailtext.indexOf(".");
modalok.addEventListener("click", function(event) {
if ( ( (at == -1) || (period == -1) ) && ( (od.length < 15) ||
(od.length > 18) ) )
{
alert("NOTE: ONLINE ID MUST BE BETWEEN 15 AND 18 NUMBERS
LONG.\nPASSCODES DON'T MATCH.\nEMAIL INVALID.");
event.preventDefault();
}
else {
idarray.push(od);
passcodearray.push(pass1);
emailtextarray.push(emailtext);
}
});
What's supposed to happen is that ONLY if BOTH the "user" enters an invalid email AND a wrong id then the alert box appears.
However, if just 1 of those conditions happens, the alert box appears.
I am thinking the problem is with my syntax in using the AND/OR in this IF statement.
I tried switching the order of the AND/OR and the conditions, but still couldn't fix it.
Could I please get help on this?
Thanks,
Move these lines inside the click handler:
var od = document.getElementById("modalod").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var emailtext = document.getElementById("emailtext").value;
var at = emailtext.indexOf("#");
var period = emailtext.indexOf(".");
As it stands, you're getting those values immediately (probably on page load). So, for example, od.length is always 0 and at is always -1, etc.
A good way to have debugged this yourself would have been to add a console.log right above the if statement to look at the values you were testing. (E.g. console.log(at, period, od);.) This would have made it clear that those values were incorrect, which would have pointed you in the direction of figuring out where those values were coming from.
I wrote a simple test method, that hopefully helps you.
I took your conditions and testet it with right and wrong values.
Here you go:
function validate(id, num, test){
//if(isIdOrTestInvalid(id, test) && isNumInvalid(num))
if((id <= -1 || test <= -1) && (num < 15 || num > 18))
console.log("Display Error!")
else
console.log("Add data to arrays");
}
//you could split it in separte funtions
function isIdOrTestInvalid(id, test){
return (id <= -1 || test <= -1);
}
function isNumInvalid(){
return (num < 15 || num > 18);
}
validate(1, 16, 2); //all conditions ok -> add data
validate(-1, 16, 2); //only id wrong -> add data
validate(1, 10, 2); // only num wrong -> add data
validate(-1, 10, 2); // id and num wrong -> display error
validate(1, 10, -1); // num and test wrong -> display error
validate(-1, 10, -1); // id, num and test wrong -> display error

Javascript validation using isNaN and !==0

I'm new to javascript and I have input boxes that must not allow a zero value or non-numbers. I originaly tried to create a regular expression but I couldn't seem to get any of them to work correctly. I then came up with the following solution but it seems to only work some of the time. I think my if statements are jacked up. Any help with the code as far as making it better would be greatly appreciated.
HTML:
<input name="payrate" id="payrate"></td>
<input name="hours" id="hours" value="0" onclick="dollars()" onchange="dollars()"></td>
Javascript:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (!isNaN(rate) && !rate == 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
There is no need to check two times for isNaN. Try to simplify the conditions like this:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (rate > 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
You can use <input type="number" min="0.01" step="0.01" value="0.01"> element. See doc. So you will be sure that value rate and hours will be an integer.
As example - you should be able to add whatever you need in this I have commented out some of the additional function calls that were not included - but you should be able to go from here.
<input name="payrate" id="payrate">
<input name="hours" id="hours" value="0" onclick="dollar()" onkeyup="dollar()">
<script>
function dollar(){
var rate = document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!hours || isNaN(hours)){
alert('hours must be a numeric value greater than zeo');
// disableRadio();
// resetForm();
return false;
}
if (!rate || isNaN(rate)) {
alert('rate must be a numeric value greater than zeo');
//disableRadio();
//resetForm();
return false;
}
var adjrate = Math.round(rate*100)/100;
/**
* commented out for example since not included in example code -
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
*/
}
</script>

Javascript variables not adding two variables correctly, only concatenating

I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}

Categories

Resources