Javascript validation using isNaN and !==0 - javascript

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>

Related

Javascript restrict input once 2 decimal places have been reached

I currently have a number input script that behaves similar to a calculator with the way numbers are displayed, but I want to stop the adding of additional numbers to the series after two numbers past the decimal point.
Here is what I have so far, though the limiting doesn't occur correctly.
It should work like this:
1.25 - Allowed
12.5 - Allowed
125.5 - Allowed
125.55 - Allowed
123.555 - Not Allowed
rText = document.getElementById("resultText");
function selectNumber(num) {
if (!rText.value || rText.value == "0") {
rText.value = num;
}
else {
this part works...
rText.value += num;
}
}
}
but this part doesn't work... Any ideas???
if (rText.value.length - (rText.value.indexOf(".") + 1) > 2) {
return false;
} else {
rText.value += num;
}
}
}
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
<input type="text" id="resultText" oninput="validate(this)" />
Save the previous value in some data attribute and if it exceeds 2 decimal places then restore the previous value
The 2 decimal places can be checked using Math.round(tis.value*100)/100!=tis.value
Note:
I have used oninputto validate even in copy paste scenarios
function restrict(tis) {
var prev = tis.getAttribute("data-prev");
prev = (prev != '') ? prev : '';
if (Math.round(tis.value*100)/100!=tis.value)
tis.value=prev;
tis.setAttribute("data-prev",tis.value)
}
<input type="number" id="rText" oninput="restrict(this);" />
I love to use Math.floor and toFixed() to resolve my decimal issues.
Here is a example:
var value = 123.5555
var roundedNumber = (Math.floor(value * 100) / 100).toFixed(2)
roundedNumber will be "123.55" as a string. So if you want as a number just add:
var value = 123.5555
var roundedNumber = Number((Math.floor(value * 100) / 100).toFixed(2))
and now you have value as a number and fixed to up 2 decimal places.
Just copy paste this method and call this method on your respective button on which button you have to check this decimal validation.
function CheckDecimal(inputtxt)
{
var decimal= /^[-+]?[0-9]+\.[0-9]+$/;
if(inputtxt.value.match(decimal))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong...!')
return false;
}
}

GST number validatoin in jquery

I want to do GST validation in javascript or jquery
Its limited to india only.
the structure of GST in India is as follows
GST Number will be of 15 digits having below validations:
a. First two positions will be numeric
b. Third to Sixth positions will be Alphabets
c. Seventh position will be either alphabet or numeric
d. Eighth to Eleventh positions will be numeric
e. Twelfth position will be an alphabet
f. Thirteenth to Fifteenth positions will be alphanumeric
([0-9]{2}[a-z]{4}([a-z]{1}|[0-9]{1}).[0-9]{3}[a-z]([a-z]|[0-9]){3}) Here is the regex for GST validation
http://regexr.com/ Test your GSTvalues with the above regex.
Here is the regex for GST validation in JavaScript:
var reggst = /^([0-9]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([0-9]){1}([a-zA-Z]){1}([0-9]){1}?$/;
if(!reggst.test(gstinVal) && gstinVal!=''){
alert('GST Identification Number is not valid. It should be in this "11AAAAA1111Z1A1" format');
}
Finally i got GST validation regular expression with handle 15 digit only :)
/^([0-9]{2}[a-zA-Z]{4}([a-zA-Z]{1}|[0-9]{1})[0-9]{4}[a-zA-Z]{1}([a-zA-Z]|[0-9]){3}){0,15}$/
$('#gst').on('change', function () {
var statecode = $(this).val().substring(0, 2);
var pancarno = $(this).val().substring(2, 12);
var entityNumber = $(this).val().substring(12, 13);
var defaultZvalue = $(this).val().substring(13, 14);
var checksumdigit = $(this).val().substring(14, 15);
if ($(this).val().length != 15) {
alert('GST Number is invalid');
$(this).focus();
return false;
}
if (pancarno.length != 10) {
alert('GST number is invalid ');
$(this).focus();
return false;
}
if (defaultZvalue !== 'Z') {
alert('GST Number is invalid Z not in Entered Gst Number');
$(this).focus();
}
if ($.isNumeric(statecode)) {
$('#gst_state_code').val(statecode).trigger('change');
} else {
alert('Please Enter Valid State Code');
$(this).focus();
}
if ($.isNumeric(checksumdigit)) {
return true;
} else {
alert('GST number is invalid last character must be digit');
$(this).focus();
}
});
Regex for GSTIN validation
/^([0-2][0-9]|[3][0-7])[A-Z]{3}[ABCFGHLJPTK][A-Z]\d{4}[A-Z][A-Z0-9][Z][A-Z0-9]$/
let vGST = (gnumber)=>{
let gstVal = gnumber;
let eMMessage = "No Errors";
let statecode = gstVal.substring(0, 2);
let patternstatecode=/^[0-9]{2}$/
let threetoseven = gstVal.substring(2, 7);
let patternthreetoseven=/^[A-Z]{5}$/
let seventoten = gstVal.substring(7, 11);
let patternseventoten=/^[0-9]{4}$/
let Twelveth = gstVal.substring(11, 12);
let patternTwelveth=/^[A-Z]{1}$/
let Thirteen = gstVal.substring(12, 13);
let patternThirteen=/^[1-9A-Z]{1}$/
let fourteen = gstVal.substring(13, 14);
let patternfourteen=/^Z$/
let fifteen = gstVal.substring(14, 15);
let patternfifteen=/^[0-9A-Z]{1}$/
if (gstVal.length != 15) {
eMMessage = 'Length should be restricted to 15 digits and should not allow anything more or less';
}else if (!patternstatecode.test(statecode)) {
eMMessage = 'First two characters of GSTIN should be numbers';
}else if (!patternthreetoseven.test(threetoseven)) {
eMMessage = 'Third to seventh characters of GSTIN should be alphabets';
}else if (!patternseventoten.test(seventoten)) {
eMMessage = 'Eighth to Eleventh characters of GSTIN should be numbers';
}else if (!patternTwelveth.test(Twelveth)) {
eMMessage = 'Twelveth character of GSTIN should be alphabet';
}else if (!patternThirteen.test(Thirteen)) {
eMMessage = 'Thirteen characters of GSTIN can be either alphabet or numeric';
}else if (!patternfourteen.test(fourteen)) {
eMMessage = 'fourteen characters of GSTIN should be Z';
}else if (!patternfifteen.test(fifteen)) {
eMMessage = 'fifteen characters of GSTIN can be either alphabet or numeric';
}
console.log(eMMessage)
}
vGST("33");
vGST("12ABCDE1234K11S");
vGST("12ABCDE1234K1ZS");
var reggst = /^([0-9]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([0-9]){1}([a-zA-Z]){1}([0-9]){1}?$/;
if(!reggst.test(gstinVal) && gstinVal!='' && gstinval.length!=15){
alert('GST Identification Number is not valid. It should be in this "11AAAAA1111Z1A1" format');
}
You can simply get the length of the field value and compare it with the count that you want.
You can do that with a regular expression as follows
var regex = /^\d{2}\w{4}[a-zA-Z0-9]{1}\d{3}\w{1}[a-zA-Z0-9]{3}$/i;
if (regex.test('GSTNumber')) { console.log('valid'); }
Here is the regex for GST Number validation which validate for 15 alphanumeric characters :
var regex ="\d{2}[A-Z]{5}\d{4}[A-Z]{1}\d{1}[A-Z]{1}\d{1}"
Here is a regex code that i am currently using on my project for gst number validation.
^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9]{1}Z[a-zA-Z0-9]{1}$
thank you.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).on('change',".gstinnumber", function(){
var inputvalues = $(this).val();
var gstinformat = new RegExp('^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$');
if (gstinformat.test(inputvalues)) {
return true;
} else {
alert('Please Enter Valid GSTIN Number');
$(".gstinnumber").val('');
$(".gstinnumber").focus();
}
});
</script>
I use this functions in my code
function check_gst(gst){
if(gst.length != 15){
alert("Invalid Length of GSTIN");
return false;
}else{
var state = parseInt(gst.substring(0, 2));
// FIRST 2 CHARACTERS STATE CODE
if(state < 1 || state > 37){
alert("Invalid First Two Characters of GSTIN");
return false;
}
// NEXT 10 CHARACTERS PAN NO. VALIDATION
var pan = gst.substring(2, 12).toUpperCase();
var regex = /[a-zA-Z]{3}[PCHFATBLJG]{1}[a-zA-Z]{1}[0-9]{4}[a-zA-Z]{1}$/;
if( !regex.test(pan) ){
alert("Invalid GSTIN");
return false;
}
// DEFAULT 14TH CHARACTER 'Z'
var char14 = gst[13].toUpperCase();
if(char14 != "Z"){
alert("14th character of GSTIN should be 'Z'");
return false;
}
// CHECKSUM DIGIT
if(check_gst_checksum(gst.substring(0, 14)) != gst[14]){
alert("Invalid GSTIN");
return false;
}
return true;
}
}
String.prototype.getw = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
function check_gst_checksum(gst_wo){
weight_c = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
gst = gst_wo.toUpperCase();
var total_a1 = 0;
for (var i = 0; i < gst.length; i++) {
var weight = weight_c.getw(gst[i]);
var factor = ( (i % 2) +1 );
var product = weight * factor;
var qu = Math.floor( product/36 );
var re = product % 36;
var a1 = qu + re;
total_a1 += a1;
}
var d = total_a1 % 36;
var dd = 36 - d;
return weight_c[dd];
}
All the calculation for checksum digit is given at this blog
https://gauravj75.blogspot.in/2018/01/excel-gstin-checksum-digit-logic.html
It's too late to respond but someone will help this.
First two Digits-The first digit of GSTIN is state code as per Indian Census 2011. The state codes are as below.
01-Jammu and Kashmir, 02-Himachal Pradesh, 03-Punjab, 04-Chandigarh, 05-Uttarakhand, 06-Haryana, 07-Delhi, 08-Rajastan, 09-UP, 10-Bihar, 11-Sikkim, 12-Arunachal Pradesh, 13-Nagaland, 14-Manipur, 15-Mizoram, 16-Tripura, 17-Meghalaya, 18-Assam, 19-West Bengal, 20-Jharkhand, 21-Orrissa, 22-Chattisgarh, 23-MP, 24-Gujarat, 25-Daman and Diu, 26-Dadar and Nagar Haveli, 27-Maharashtra, 28-Andhra Pradesh, 29-Karnataka, 30-Goa, 31-Lakshadweep, 32-Kerala, 33-Tamil Nadu, 34-Puducherry and 35-Anadaman and Nicobar Islands.
Next 10 Digits-It is the PAN number of a business entity like your shop, mall or company.
13th Digit-It indicates the number of registrations as a business entity has within a state for the same PAN. It will be an alpha-numeric number (first 1-9 and then A-Z) and will be assigned on the basis of the number of registrations a legal entity (having the same PAN) has within one state.
Let say the company ABC registered in the same state for 5 times for different businesses. In such case, this digit will be printed as 5. Let us assume, the same company registered for around 15 times, then it should be represented as F (1-9 numeric and later on 10th registration be named as A and 11th as B and so on up to Z).
Hence, a business entity can register the GSTIN within a single state for the maximum of 35 times (1-9 and later on A-Z).
14th Digit-It will be by default as Z.
15th Digit-The last digit will be a check code which will be used for detection of errors.
With this information working RegEX is below
^[0-9]{2}[A-Za-z]{3}[CPHFATBLJGcphfatblj]{1}[A-Za-z]{1}[0-9]{4}[A-Za-z]{1}[0-9A-Za-z]{1}(Z|z)[0-9A-Za-z]{1}$
This is perfect GST Validation code.
This will definitely work with your jQuery.
rules: {
gst_number_value: {
required: true,
minlength: 15,
maxlength: 15,
pattern: '^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9]{1}[A-Z]{2}$',
},
},
messages: {
required: "Please enter GST number",
minlength: "Please check your GST number.",
maxlength: "Please check your GST number.",
pattern: "You have entered an invalid GST number.",
},

Random number is not staying within range javascript [duplicate]

This question already has an answer here:
Javascript Addition wont work
(1 answer)
Closed 5 years ago.
I have made a Random Number Guess game. The user has to set the minimum and maximum range the random number can be generated in and the number of attempts they get changes dependent on the size of the range they have set. So if the user enters in a minimum of 1 and a maximum of 100 the range will be divided by 10 and rounded up to give the user 10 attempts to guess the number.
The problem I have is that the random number being generated is always way out of the set range and I am not sure why.
My javascript code:
winner = "Well done, you guessed the number correctly";
loser = "Unfortunately you did not guess the number correctly. Game Over!";
higher = "Your guess was too low. Guess higher";
alreadyWon = "You have already guessed correctly. Press f5 to play again";
lower = "Your guess was too high. Guess lower";
gameWon = false;
counter = 0;
function processingFunction(minRange, maxRange) {
randomNo = Math.floor(Math.random() * (maxRange - minRange)) + minRange; //random number generated
attempts = Math.round((maxRange - minRange) / 10); //number of attempts generated
return (randomNo, attempts);
}
function showFunction(guess) {
if (gameWon == true) {
document.getElementById("output1").innerHTML = alreadyWon;
} else if (counter < attempts) {
if (guess == randomNo) {
document.getElementById("output1").innerHTML = winner;
gameWon = true;
} else if (guess > randomNo) {
document.getElementById("output1").innerHTML = lower;
} else {
document.getElementById("output1").innerHTML = higher;
}
counter++;
} else {
document.getElementById("output1").innerHTML = loser;
}
}
<center>
<h2>Random Number Guess</h2>
</center>
<h3>Enter in the minimum range and the maximum range. Accompanied by your first guess</h3>
Minimum Range:<input type="text" id="inputMinRange"></input> Maximum Range:<input type="text" id="inputMaxRange"></input>
<button type="button" onclick="processingFunction(document.getElementById('inputMinRange').value, document.getElementById('inputMaxRange').value)">Set Range</button>
<br><br>
<input type="text" id="guessInput"></input>
<button type="button" onclick="showFunction(document.getElementById('guessInput').value)">Guess</button>
<pre type="text" id="output1"></pre>
The value of an input is always a string, and when you use + where one of the operands is a string, you get string concatenation, not addition. (- will coerce to number, but + will not.) So say we fill in 1 and 100. This:
randomNo = Math.floor(Math.random() * (maxRange - minRange)) + minRange; //random number generated
...takes maxRange - minRange and gets 99 (so far so good), multiplies that by a random value to get (say) 83, and then appends "1" to it to get "831".
You want to convert those values to numbers before feeding them into the function. There are lots of ways to do that (see this answer for a rundown of them, but for instance, the unary +:
<button type="button" onclick="processingFunction(+document.getElementById('inputMinRange').value, +document.getElementById('inputMaxRange').value)">Set Range</button>
<!-- ---------------------------------------------^------------------------------------------------^ -->
Now the function is working with numbers throughout.
Updated snippet:
winner = "Well done, you guessed the number correctly";
loser = "Unfortunately you did not guess the number correctly. Game Over!";
higher = "Your guess was too low. Guess higher";
alreadyWon = "You have already guessed correctly. Press f5 to play again";
lower = "Your guess was too high. Guess lower";
gameWon = false;
counter = 0;
function processingFunction(minRange, maxRange) {
randomNo = Math.floor(Math.random() * (maxRange - minRange)) + minRange; //random number generated
attempts = Math.round((maxRange - minRange) / 10); //number of attempts generated
console.log(minRange, maxRange, randomNo, attempts);
return (randomNo, attempts);
}
function showFunction(guess) {
if (gameWon == true) {
document.getElementById("output1").innerHTML = alreadyWon;
} else if (counter < attempts) {
if (guess == randomNo) {
document.getElementById("output1").innerHTML = winner;
gameWon = true;
} else if (guess > randomNo) {
document.getElementById("output1").innerHTML = lower;
} else {
document.getElementById("output1").innerHTML = higher;
}
counter++;
} else {
document.getElementById("output1").innerHTML = loser;
}
}
<center>
<h2>Random Number Guess</h2>
</center>
<h3>Enter in the minimum range and the maximum range. Accompanied by your first guess</h3>
Minimum Range:<input type="text" id="inputMinRange"></input> Maximum Range:<input type="text" id="inputMaxRange"></input>
<button type="button" onclick="processingFunction(+document.getElementById('inputMinRange').value, +document.getElementById('inputMaxRange').value)">Set Range</button>
<br><br>
<input type="text" id="guessInput"></input>
<button type="button" onclick="showFunction(document.getElementById('guessInput').value)">Guess</button>
<pre type="text" id="output1"></pre>
use below code to convert you are passing a string and + will append the minRange string with generated random no.
randomNo = Math.floor(Math.random() * (maxRange - minRange))+Math.round(minRange);
or
randomNo = Math.floor(Math.random() * (maxRange - minRange))-(-minRange);

wrong error message output in function

I am trying to validate a Poperty value and down payment. The conditions are as follows:
property value:
Must be present
Must be numeric - positive - whole number
Must be at least 65,000 dollars more that the down payment.
down payment:
Must be present
Must be numeric - positive - whole number
Must be at least 20% of the value of the property (propValue)
My function is (sort of) working. It doesn't pass all the validation tests. If someone can point me in the right direction as to how to improve this it would be greatly appreciated. My 2 functions for the down pay and value:
function propValueValidation(errMessages){
var propValueLength = document.mortgage.propValue.value.length;
var propValueNumber = isNaN(document.mortgage.propValue.value);
var propValue = document.mortgage.propValue.value;
var downPayPlus = document.mortgage.downPay.value + 65000;
if (!propValueLength) {
errMessages += " Property Value is a required field";
return errMessages;
}
else if (typeof propValue === 'number') {
var remainder = (propValue % 1);
if(remainder != 0){
errMessages += "Property Value must be a positive whole number";
return errMessages;
}
}
else if (propValue < downPayPlus){
errMessages += "Property Value must be at least 65,000 greater than the down payment";
return errMessages;
}
return errMessages;
}
//validate down pay
function downPayValidation(errMessages){
var downPayLength = document.mortgage.downPay.value.length;
var downPay = document.mortgage.downPay.value;
var propValueMin = document.mortgage.propValue.value * 0.2;
if (!downPayLength) {
errMessages += "Down Payment is a required field";
return errMessages;
}
else if (typeof downPay === 'number') {
var remainder = (downPay % 1);
if(remainder != 0){
errMessages += "Down Payment must be a positive whole number";
return errMessages;
}
}
else if (downPay < propValueMin){
errMessages +="Down Payment must be at least 20% of the property value";
return errMessages;
}
return errMessages;
}
HTML:
<label class="label">Property Value </label>
<input type="text" name="propValue" id="propValue" size="7" maxlength="6" >
<br>
<label class="label">Down Payment </label>
<input type="text" name="downPay" id="downPay" size="7" maxlength="6" >
when downpay is "1nn1" it will still submit the form for example. Thanks!
you can use parseInt() to confirm its a number.
var tempVal = document.mortgage.propValue.value;
var propValue = parseInt(tempVal); // this will try to extract an integer from tempVal
if (tempVal != propValue.toString()) // if true, there were non-number chars or value is NaN
{
errMessages += "Bad value, please enter an integer";
}
You should not use isNaN on string values (which input values are). Instead first convert such a string to number with Number() (or parseFloat, but Number will require the whole of the input to parse as number, while parseFloat or parseInt will accept strings that start with a number). Then call isNaN on that.
There is also a problem with the if else logic, because you have one branch for numeric data (where it will never get, because the value property of input elements is always a string), and an else on that to compare the amount with another amount. Yet for that last test the value must be numeric. So that test is in the wrong place.
Here is your first function's code with some alterations made:
function propValueValidation(errMessages){
var propValue = document.mortgage.propValue.value;
var propValueNumber = Number(propValue);
var downPayPlus = propValueNumber + 65000;
var genericMsg = ' property value was provided. Please provide a positive' +
' whole number, at least 65,000 greater than the down payment.\n';
if (!propValue.length) {
errMessages += 'No' + genericMsg;
} else if (isNaN(propValueNumber)) {
errMessages += 'A non-numerical' + genericMsg;
} else if (propValueNumber % 1) {
errMessages += 'A fractional' + genericMsg;
} else if (propValueNumber < downPayPlus){
errMessages += 'A too small' + genericMsg;
}
return errMessages;
}

validate input field before submitting form

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
}

Categories

Resources