I (total Javascript Noob) am trying to write a javascript to create a weight and balance calculator for general aviation aircraft.
However I am getting stuck along the way.
The user is supposed to enter weight information and the calculator should then calculate the airplanes Moment and or weight as well as sum up the corresponding fields.
Unfortunately I can't get the script to calculate the users inputs. Does anyone have a suggestion?
My HTML is: (JS further down below)
<form id="form" onsubmit="return false;">
<table>
<tr>
<th>Station</th>
<th>Weight</th>
<th></th>
<th>Arm</th>
<th></th>
<th>Moment</th>
<th></th>
</tr>
<tr>
<td>Empty Weight</td>
<td>
<script type="text/javascript">
document.write(weight);
</script>
</td>
<td>kg</td>
<td>
<script type="text/javascript">
document.write(acarm);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(moment);
</script>
</td>
<td>m</td>
</tr>
<tr>
<td>Pilot</td>
<td>
<input type="text" value="0" onkeypress="return isNumberKey(event)" onblur="onBlur(this)" onfocus="onFocus(this)" id="Pilot" />
</td>
<td>kg</td>
<td>
<script type="text/javascript">
document.write(afseat);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(pimom);
</script>
</td>
<td>m</td>
</tr>
<tr>
<td>CoPilot</td>
<td>
<input type="text" value="0" onkeypress="return isNumberKey(event)" onblur="onBlur(this)" onfocus="onFocus(this)" id="CoPilot" />
</td>
<td>kg</td>
<td>
<script type="text/javascript">
document.write(afseat);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(cpmom);
</script>
</td>
<td>m</td>
</tr>
<tr>
<td>Pax 1</td>
<td>
<input type="text" value="0" onkeypress="return isNumberKey(event)" onblur="onBlur(this)" onfocus="onFocus(this)" id="Pax1" />
</td>
<td>kg</td>
<td>
<script type="text/javascript">
document.write(arseat);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(p1mom);
</script>
</td>
<td>m</td>
</tr>
<tr>
<td>Pax 2</td>
<td>
<input type="text" value="0" onkeypress="return isNumberKey(event)" onblur="onBlur(this)" onfocus="onFocus(this)" id="Pax2" />
</td>
<td>kg</td>
<td>
<script type="text/javascript">
document.write(arseat);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(p2mom);
</script>
</td>
<td>m</td>
</tr>
<tr>
<td>Fuel</td>
<td>
<input type="text" value="0" onkeypress="return isNumberKey(event)" onblur="onBlur(this)" onfocus="onFocus(this)" id="Fuel" />
</td>
<td>l</td>
<td>
<script type="text/javascript">
document.write(abag);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(bamom);
</script>
</td>
<td>m</td>
</tr>
<tr>
<td>Baggage</td>
<td>
<input type="text" value="0" onkeypress="return isNumberKey(event)" onblur="onBlur(this)" onfocus="onFocus(this)" id="Baggage" />
</td>
<td>kg</td>
<td>
<script type="text/javascript">
document.write(abag);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(bamom);
</script>
</td>
<td>m</td>
</tr>
<tr>
<td>Total</td>
<td>
<script type="text/javascript">
document.write(totweight);
</script>
</td>
<td>kg</td>
<td>
<script type="text/javascript">
document.write(totarm);
</script>
</td>
<td>kg-m</td>
<td>
<script type="text/javascript">
document.write(totmom);
</script>
</td>
<http://jsfiddle.net/#savetd>m</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" onclick="weightandbalance();" />
</td>
<td></td>
<td></td>
</tr>
</table>
And here is the JS:
// Basic Aircraft Set Up
var weight = 627.9; // Basic Empty Weight in kg
var moment = 201.22; // Moment in m-kg
var acarm = Math.round((moment / weight) * 10000) / 10000;
var mtow = 1002; // Maximum Take Off Weight in kg
var afseat = 0.41; // Front Seat Arm in m
var arseat = 1.19; // Rear Seat Arm in m
var abag = 1.9; // Baggage Area Arm in m
var afuel = 1.12; // Fuel Tank Arm in m
function weightandbalance() {
var Pilot = parseFloat(document.getElementById("Pilot").value);
var CoPilot = document.getElementById("CoPilot").value;
var Pax1 = document.getElementById("Pax1").value;
var Pax2 = document.getElementById("Pax2").value;
var Baggage = document.getElementById("Baggage").value;
var Fuel = document.getElementById("Fuel").value;
// Perform Calculations
var pimom = Pilot * afseat;
var cpmom = CoPilot.value * afseat;
var p1mom = Pax1.value * arseat;
var p2mom = Pax2.value * arseat;
var bamom = Baggage.value * abag;
var fumom = Fuel.value * afuel * 0.71;
var totweight = weight + Pilot + CoPilot + Pax1 + Pax2 + Baggage + Fuel;
var totmom = moment + pimom + cpmom + p1mom + p2mom + bamom + fumom;
var totarm = Math.round((totmom / weight) * 10000) / 10000;
}
// Allow only numbers
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false;
return true;
}
//Default Values
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
You may want to put a console.log() statement in your code somewhere and open the developer console for your browser to see what it prints out.
For example, put it after you calculate totweight or something:
var totweight = weight + Pilot + CoPilot + Pax1 + Pax2 + Baggage + Fuel;
console.log(totweight);
If you're using Chrome, you can open the console by pressing CtrlShiftJ (Windows) or CmdOptJ (Mac).
Another thing you may want to do is to do parseFloat() on your other variables like you did for the Pilot variable. You may be getting back strings instead of numbers in your code snippet here. So you could do something like this:
console.log(typeof CoPilot);
And see what the console prints out in the browser. If it prints out "string" instead of "number", you'll know to ParseFloat() those variables as well.
You can also do the following to check if CoPilot (or any other variable) is Not-A-Number:
console.log( isNan(CoPilot) );
I hope this helps.
Related
My Requirment:
I have table with quantity cell as editable when change quantity it need to multiply with other parent td value.and sum the column values .
(i.e) if i change quantity to 2 then the parent rows need multiply by 2 & columns get value get added
I done all the calculation part the only thing when i delete or change the quantity the calculated value remain same how to revert back to old values
Here is my fiddle
Fiddle link
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
<!-- console.log(preVal); -->
if(preVal && preVal == val){
return;
}
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1){
return;
}
$(this).siblings().each(function(){
var tbvalue=$(this).text();
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
})
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i < 8; i++) {
var sum = 0;
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').each(function() {
sum += parseInt($(this).text()) || 0;
});
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>5</td>
<td>4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>8</td>
<td type>2</td>
<td>3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>20</td>
<td>3</td>
<td>5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
Inside every row, with the td that store the numbers to be multiplied, keep the original numbers in a data-val attribute in the td, and multiply your content editable value with that. Display the multiplied value as the td text. One change here is that, when you delete the value of contenteditable cell, it takes it as 1 for row calculation, but does not consider it for column multiplication.
HTML part
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td data-val="10">10</td>
<td data-val="5">5</td>
<td data-val="4">4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="8">8</td>
<td data-val="2">2</td>
<td data-val="3">3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="20">20</td>
<td data-val="3">3</td>
<td data-val="5">5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
JS Part
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1 || val == undefined){
val = 1;
}
$(this).siblings().each(function(){
var tbvalue=$(this).data("val");
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
});
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i <= 4; i++) {
var sum = 0;
var tdBoxes = $('.auto_sum>tbody>tr>td:nth-child(' + i + ')');
for(var j=0; j<tdBoxes.length-1;j++)
{
var value = $(tdBoxes[j]).text();
//alert(value);
sum += (value == undefined || value == "")? 0 : parseInt(value);
}
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
All details are commented in working demo. I added <form>, <output>, <input type='number'> and <input type='hidden'>. Also I don't remember <td> having a type attribute or a value of number either.
With the combination of the right elements and attributes (and maybe even a little CSS), you don't have to write so much JS/jQ because there many aspects of form functions built within HTML.
Demo
// Reference the <form>
var main = document.forms.main;
// Reference of all of <input> and <output> of <form>
var field = main.elements;
/* Register the input event on the <form>
|| ANY input event triggered within <form> will...
*/
main.addEventListener('input', function(e) {
// Check to see which field is the user inputing into
if (e.target !== e.currentTarget) {
// Reference that field
var input = document.getElementById(e.target.id);
// console.log(input.value);
// Get the row of the field
var row = input.parentNode.parentNode;
// console.log(row);
/* Gather all hidden fields of that row into a NodeList
|| and convert that NodeList into an array.
*/
var rowArray = Array.from(row.querySelectorAll('[type=hidden]'));
// console.log(rowArray);
// On each hidden field, perform the following function...
rowArray.forEach(function(cel, idx) {
// Get the value of hidden field
const base = cel.value;
// Find the <output> that comes after the hidden field
var output = cel.nextElementSibling;
/* Calculate the product of the hidden field's value
|| and the input field's value
*/
var val = parseInt(base, 10) * parseInt(input.value, 10);
// Display the prouct in the <output>
output.value = val;
});
/* Because we registered the input event on the <form>,
|| we have many ways to manipulate the <form>'s fields.
|| In this demo we have been using:
|| HTMLFormElement and HTMLFormControlsCollection interfaces
|| https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
|| http://www.dyn-web.com/tutorials/forms/references.php#dom0
*/
field.out1.value = Number(field.o1a.value) + Number(field.o1b.value) + Number(field.o1c.value);
field.out2.value = Number(field.o2a.value) + Number(field.o2b.value) + Number(field.o2c.value);
field.out3.value = Number(field.o3a.value) + Number(field.o3b.value) + Number(field.o3c.value);
field.out4.value = Number(field.out1.value) + Number(field.out2.value) + Number(field.out3.value);
}
});
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
input,
output {
display: inline-block;
font: inherit;
width: 6ch;
border: 0;
text-align: center;
}
.quantity input {
padding-top: .5em;
outline: 0;
}
-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="container">
<form id='main'>
<table class="auto_sum table table-hover">
<thead>
<caption>
<h2>Table Calculation</h2>
<h3>Quanities</h3>
</caption>
<tr>
<th>Value1</th>
<th>Value2</th>
<th>Value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr id='rowA'>
<td>
<!--[0][1]-->
<input id='v1a' type='hidden' value='10'>
<output id='o1a'>0</output>
</td>
<td>
<!--[2][3]-->
<input id='v2a' type='hidden' value='5'>
<output id='o2a'>0</output>
</td>
<td>
<!--[4][5]-->
<input id='v3a' type='hidden' value='4'>
<output id='o3a'>0</output>
</td>
<td class="quantity">
<!--[6]-->
<input id='qa' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowB'>
<td>
<!--[7][8]-->
<input id='v1b' type='hidden' value='8'>
<output id='o1b'>0</output>
</td>
<td>
<!--[9][10]-->
<input id='v2b' type='hidden' value='2'>
<output id='o2b'>0</output>
</td>
<td>
<!--[11][12]-->
<input id='v3b' type='hidden' value='3'>
<output id='o3b'>0</output>
</td>
<td class="quantity">
<!--[13]-->
<input id='qb' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowC'>
<td>
<!--[14][15]-->
<input id='v1c' type='hidden' value='20'>
<output id='o1c'>0</output>
</td>
<td>
<!--[16][17]-->
<input id='v2c' type='hidden' value='3'>
<output id='o2c'>0</output>
</td>
<td>
<!--[18][19]-->
<input id='v3c' type='hidden' value='5'>
<output id='o3c'>0</output>
</td>
<td class="quantity">
<!--[20]-->
<input id='qc' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr class="total">
<td>
<!--[21]-->
<output id='out1' for='o1a o1b o1c'>0</output>
</td>
<td>
<!--[22]-->
<output id='out2' for='o2a o2b o2c'>0</output>
</td>
<td>
<!--[23]-->
<output id='out3' for='o3a o3b o3c'>0</output>
</td>
<td>
<!--[24]-->
<output id='out4' for='out1 out2 out3'>0</output>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
i cant get both values on selecting dropdown options. Only one output gives not both. Please help to solve this. i want to show value in output field when i select fahrenheiet it should give in celsius and vice versa.
<script type="text/javascript">
function findCelsius()
{
var vals = document.getElementById("convert").value;
if(vals = "F"){
var v = document.getElementById("vlues").value;
var celsius = (v - 32) * 5/9;
var result = Math.ceil(celsius);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Farenheit to Celsius!";
}
else if(vals = "C")
{
var va = document.getElementById("vlues").value;
var fah = (va * 9/5) + 32;
var result = Math.ceil(fah);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Celsius to Fahrenheit!";
}
}
</script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Conversion</title>
</head>
<body>
<h2>Convert Temprature</h2>
<form name="conversion">
<table>
<tr>
<td>
Enter a Value
</td>
<td>
<input type="number" name="vlue" value="" id="vlues">
<select id="convert" onChange="findCelsius()">
<option value="F">Farenheight(F°)</option>
<option value="C">Celsius(C°)</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="text" id="answer" name="result" value="">
</td>
</tr>
<tr>
<td>
Answer:
</td>
</tr>
<tr>
<td>
</td>
<td>
<span id="output"></span>
</td>
</tr>
</table>
</form>
</body>
</html>
If Condition declaration was wrong use == instead =
function findCelsius() {
var vals = document.getElementById("convert").value;
if (vals == "F") {
var v = document.getElementById("vlues").value;
var celsius = (v - 32) * 5 / 9;
var result = Math.ceil(celsius);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Farenheit to Celsius!";
} else if (vals == "C") {
var va = document.getElementById("vlues").value;
var fah = (va * 9 / 5) + 32;
var result = Math.ceil(fah);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Celsius to Fahrenheit!";
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Conversion</title>
</head>
<body>
<h2>Convert Temprature</h2>
<form name="conversion">
<table>
<tr>
<td>
Enter a Value
</td>
<td>
<input type="number" name="vlue" value="" id="vlues">
<select id="convert" onChange="findCelsius()">
<option value="">select</option>
<option value="F">Farenheight(F°)</option>
<option value="C">Celsius(C°)</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="text" id="answer" name="result" value="">
</td>
</tr>
<tr>
<td>
Answer:
</td>
</tr>
<tr>
<td>
</td>
<td>
<span id="output"></span>
</td>
</tr>
</table>
</form>
</body>
</html>
I'm new to HTML and Javascript, I managed to create the table and slider how I want them. However I'd like the script to be universal, so it can be used on other tables with different values and with more or less rows. I assume that means it will have to create an array from the number of rows and their values?
Any help would be greatly appreciated!
<html>
<body onload="myFunction()">
<table>
<tr>
<td>value one</td>
<td id="value1">0.5</td>
</tr>
<tr>
<td>value two</td>
<td id="value2">5</td>
</tr>
<tr>
<td>value three</td>
<td id="value3">2</td>
</tr>
</table>
<form id="myForm">
<input type="range" id="myRange" defaultvalue="1" value="1" min="0.1" max="2" step="0.1" onclick="myFunction()">
<input type="button" onclick="myReset();myFunction()" value="Reset">
</form>
<script>
function myReset() {
document.getElementById("myForm").reset();
}
function myFunction() {
var x = document.getElementById("myRange").value;
var value1 = 0.5 * x; //entered values manually as I don't know how to retrieve from table cells
var v1 = value1.toFixed(2);
var value2 = 5 * x;
var v2 = value2.toFixed(2);
var value3 = 2 * x;
var v3 = value3.toFixed(2);
document.getElementById('value1').innerHTML = v1;
document.getElementById('value2').innerHTML = v2;
document.getElementById('value3').innerHTML = v3;
}
</script>
</body>
</html>
If you give all the cells the same class you can access them all using .getElementsByClassName. You can also assign a value to an attribute of the cell and then access it using .getAttribute.
Please see the snippet below as an example.
function myReset() {
document.getElementById("myForm").reset();
}
function myFunction() {
var x = document.getElementById("myRange").value;
var cells = document.getElementsByClassName("value-cell");
for(var cell of cells) {
var value = cell.getAttribute('value');
cell.innerHTML = value * x;
}
}
<html>
<body onload="myFunction()">
<table>
<tr>
<td>value one</td>
<td class="value-cell" value="0.5"></td>
</tr>
<tr>
<td>value two</td>
<td class="value-cell" value="5"></td>
</tr>
<tr>
<td>value three</td>
<td class="value-cell" value="2"></td>
</tr>
</table>
<form id="myForm">
<input type="range" id="myRange" defaultvalue="1" value="1" min="0.1" max="2" step="0.1"
onclick="myFunction()">
<input type="button" onclick="myReset(); myFunction()" value="Reset">
</form>
</body>
</html>
An alternative to using .getAttribute would be to put a hidden input inside the cell and store the value there and then access it with input.value.
You could also use jQuery and make the whole thing a little cleaner.
The icky part is finding a way to iterate through the elements, in this current solution it is assuming the elements will have increasing IDs starting with "value1". Naturally if you add a class to each element you can iterate through that way, but this should suffice to demonstrate the point.
function myReset() {
document.getElementById("myForm").reset();
}
function myFunction() {
var x = document.getElementById("myRange").value;
var count = 1;
var currentElem = document.getElementById("value" + count);
while (currentElem) {
var val = (currentElem.innerText * x).toFixed(2);
currentElem.innerHTML = val;
count++;
currentElem = document.getElementById("value" + count);
}
}
<html>
<body onload="myFunction()">
<table>
<tr>
<td>value one</td>
<td class="table-val" id="value1">0.5</td>
</tr>
<tr>
<td>value two</td>
<td class="table-val" id="value2">5</td>
</tr>
<tr>
<td>value three</td>
<td class="table-val" id="value3">2</td>
</tr>
</table>
<form id="myForm">
<input type="range" id="myRange" defaultvalue="1" value="1" min="0.1" max="2" step="0.1" onclick="myFunction()">
<input type="button" onclick="myReset();myFunction()" value="Reset">
</form>
</body>
</html>
I'm trying to use a javascript method to validate my form but it doesn't seem to be working. No dialog box pops up warning me of any errors even if an empty form is submitted. What could be the error?
(Please Note: The JS File has a method defined for a time-stamp that I am currently not using in my form tag. I need some help with calling two functions as well.)
Here's the code:
function setDate() {
document.getElementById('date').value = new Date();
}
function validateForm() {
var a = document.getElementById('name').value;
var b = document.getElementById("contact1").value;
var blen = b.length;
var c = document.getElementById("address1").value;
var d = document.getElementById("stblimit").value;
var dlen = d.length;
var e = document.getElementById("creditlimit").value;
var f = document.getElementById("commission").value;
var g = document.getElementById("servicecharges").value;
//DATE var h = document.forms["addRetailer"]["date"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
} else if (b == null || b == "" || blen == 0 || blen > 10 || blen < 10) {
alert("Enter a valid number");
return false;
} else if (c == null || c == "") {
alert("Primary Address must be filled out");
return false;
} else if (d == null || d == "" || dlen == 0 || dlen < 0) {
alert("Set Box Top Limit must be filled with a valid number");
return false;
} else if (e == null || e == "") {
alert("Credit Limit must be filled out");
return false;
} else if (f == null || f == "") {
alert("Commission Percentage must be filled out");
return false;
} else if (g == null || g == "") {
alert("Service Charges must be filled out");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="formvalidation.js" type="text/javascript"></script>
<title>Register Retailer</title>
</head>
<body>
<h1>Retailer Information</h1>
<form name="addRetailer" action="RetailerController" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" id="name"></input>
</td>
</tr>
<tr>
<td>Contact Number 1</td>
<td>
<input type="text" name="contact1" id="contact1"></input>
</td>
</tr>
<tr>
<td>Contact Number 2</td>
<td>
<input type="text" name="contact2" id="contact2"></input>
</td>
</tr>
<tr>
<td>Address Line 1</td>
<td>
<input type="text" name="address1" id="address1"></input>
</td>
</tr>
<tr>
<td>Address Line 2</td>
<td>
<input type="text" name="address2" id="address2"></input>
</td>
</tr>
<tr>
<td>City</td>
<td>
<input type="text" name="city" id="city"></input>
</td>
</tr>
<tr>
<td>State</td>
<td>
<input type="text" name="state" id="state"></input>
</td>
</tr>
<tr>
<td>Pin Code</td>
<td>
<input type="text" name="pin" id="pin"></input>
</td>
</tr>
<tr>
<td>Set Top Box Limit</td>
<td>
<input type="text" name="stblimit" id="stblimit" value="0"></input>
</td>
</tr>
<tr>
<td>Credit Limit</td>
<td>
<input type="text" name="creditlimit" id="creditlimit"></input>
</td>
</tr>
<tr>
<td>Commission Percentage</td>
<td>
<input type="text" name="commission" id="commission" value="0.0"></input>
</td>
</tr>
<tr>
<td>Service Charges</td>
<td>
<input type="text" name="servicecharges" id="servicecharges"></input>
</td>
</tr>
<tr>
<td>Date of Registration</td>
<td>
<input type="text" name="date" id="date"></input>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="hidden" value="registerCustomer" name="action"></input>
<input type="submit" value="Register"></input>
</td>
</tr>
</table>
</form>
<br>
<br>Click
Home To Return To The Main Screen
</body>
</html>
EDIT:
Here is a screenshot of my Eclipse IDE workspace. My js file and html file aren't in the same sub-folder, although they are under 'Web Content'. Could that be the issue?
Screenshot of Eclipse IDE Workspace
You may not have linked your JS file properly.
Looking at your screenshot I noticed you're using Tomcat and Java EE, which follows Unix style syntax for it's directory on the web server.
Your directory:
-Webcontent/
-WEB-INF/
+addRetailer
-JavaScript/
+validateForm.js
So, your HTML file is in WEB-INF which is under Webcontent and the form validator is under javascript, also under webcontent.
There's three solutions I have for this:
Move the JavaScript folder into WEB-INF and change the script reference to: "JavaScript/formvalidation.js"
Change the script reference to jump 'up' a directory layer using the double-dot'..' which should end up being: "../JavaScript/formvalidator.js"
Use HTML5's form validation instead, which doesn't need JavaScript. and is much neater. You can find details on the Mozilla Dev Network here.
Using Chrome, it seems to work for me:
The only thing that I changed is that I removed the link to the external JS file. It is possible the error is there and preventing your code from running. Check that file.
I have a Javascript that's running on an html form that performs some calculations based on the values the user has entered and then enters the results into some other fields. This is all working well. Here's what the HTML looks like:
<table width="100%" border="0" cellspacing="0" cellpadding="10" class="border" id="calcs">
<tr class="d_green">
<td colspan="4">LAST YEAR</td>
</tr>
<tr class="l_white">
<td width="53%">number of instances in the last year </td>
<td width="13%" align="right"><input name="textfield1" type="text" class="input_b_r" id="textfield1" value="0" /></td>
<td width="24%"> </td>
<td width="10%"> </td>
</tr>
<tr class="l_green">
<td>average number of moderate-risk activity per week in the last year</td>
<td align="right"><input name="textfield2" type="text" class="input_b_r" id="textfield2" value=""/></td>
<td> </td>
<td> </td>
</tr>
<tr class="l_white">
<td>average number of hours of high-risk activity per week in the last year</td>
<td align="right"><input name="textfield3" type="text" class="input_b_r" id="textfield3" value=""/></td>
<td> </td>
<td> </td>
</tr>
<tr class="d_green">
<td colspan="4">NEXT YEAR</td>
</tr>
<tr class="l_white">
<td>expected average number of hours of moderate-risk activity per week next year</td>
<td align="right"><input name="textfield4" type="text" class="input_b_r" id="textfield4" value=""/></td>
<td> </td>
<td> </td>
</tr>
<tr class="l_green">
<td>expected average number of hours of high-risk activity per week next year</td>
<td align="right"><input name="textfield5" type="text" class="input_b_r" id="textfield5" value=""/></td>
<td> </td>
<td> </td>
</tr>
<tr class="l_white">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr class="l_green">
<td> </td>
<td colspan="2" style="padding-left:31px;"><input type="submit" name="button" id="Calculate" value="Calculate" class="button_calculate" /></td>
<td> </td>
</tr>
<tr class="l_white">
<td> </td>
<td colspan="2" style="padding-left:105px;">predicted number of instances next year</td>
<td><input name="textfield6" type="text" class="input_b" id="textfield6" /></td>
</tr>
<tr class="l_green">
<td> </td>
<td colspan="2" style="padding-left:105px;">extra instances next year</td>
<td><input name="textfield7" type="text" class="input_b" id="textfield7" /></td>
</tr>
</table>
and here's the Javascript:
$(document).ready(function(){
$('#Calculate').click(function(){
var IRRC2 = 1.35;
var IRRC3 = 2.75;
var Npast = Number($("#textfield1").val());
var t2hrswk = Number($("#textfield2").val());
var t3hrswk = Number($("#textfield3").val());
var t2nexthrswk = Number($("#textfield4").val());
var t3nexthrswk = Number($("#textfield5").val());
var t2epyr = t2hrswk * 6 * 52;
var t3epyr = t3hrswk * 6 * 52;
var t01epyr = 52 * 7 * 24 * 6 - t2epyr - t3epyr;
var epochBaseInstances = Npast / (t01epyr + IRRC2 * t2epyr + IRRC3 * t3epyr);
var baselineCoefficient = Math.log(epochBaseInstances);
var t2nextepyr = t2nexthrswk * 6 * 52;
var t3nextepyr = t3nexthrswk * 6 * 52;
var t01nextepyr = 52 * 7 * 24 * 6 - t2nextepyr - t3nextepyr;
var predictedInstances = Math.exp(baselineCoefficient) * (t01nextepyr + IRRC2 * t2nextepyr + IRRC3 * t3nextepyr);
var roundedPredictedInstances = Math.round( predictedInstances * 10 ) / 10;
var lastYearTotal = Number($("#textfield1").val());
var extraInstancesRounded = Math.round( (roundedPredictedInstances - lastYearTotal) * 10 ) / 10;
$('#textfield6').val(roundedPredictedInstances);
$('#textfield7').val(extraInstancesRounded);
});
});
I know need to modify this so that if the value of the first form field (textfield1) is 0 when the user clicks the Calculate button it detects this and then exits, displaying an error message (e.g. "the value for Last Year cannot be zero").
Everything I've tried so far has broken the Javascript - appreciate any assistance with how to proceed.
Try this code, just after the Npast decleration:
var Npast = Number($("#textfield1").val());
if (Npast === 0) {
alert("the value for Last Year cannot be zero");
return;
}
Add this conditional statement toward the bottom:
if ( !Npast ) {
alert('Error!');
return false;
}
Here's a working demo of the fix: http://jsfiddle.net/38PGy/
Try this
var last_year = $("#textfield1").val();
if (last_year == 0) {
alert("The value for Last Year cannot be zero, please enter valid number");
return;
}
you could try adding validations for your textfields
here is a sample:
$(document).ready(function(){
$('#Calculate').on('click',function(){
if (!validateTextField()){
alert('no zeroes');
} else {
alert('zeroes');
}
});
});
function validteTextField(){
//$('input[id^=textfield]') --> selects all input with id having a prefix textfield
$('input[id^=textfield]').css('background-color','white');
var flg = false;
$('input[id^=textfield]').each(function(){
if ($(this).val() === 0 || $(this).val().length === 0){
$(this).css('background-color','pink');
flg = true;
}
});
return flg;
}
jsFiddle demo