form validation using isNaN() - javascript

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="basic">
<form id="input">
<p id="content">
<label> Birth Year: <input type="text" id="box1" placeholder="E.g. 1020" ></label> <br></br>
<!-- oninvalid="this.setCustomValidity('Please enter a number.')" -->
<label> Current Year: <input type="text" id="box2" placeholder="E.g. 1220" ></label> <br></br>
<input type="button" value="Calculate" id="submit" onclick="calculateAge(document.getElementById('box1').value, document.getElementById('box2'.value))"/>
</p>
</form>
</div>
<script type="text/javascript">
//previous attempt at form validation and bubble error message.
//error message for form fields
var birth = document.getElementById('box1');
birth.oninvalid = function(event)
{
event.target.setCustomValidity('Please enter a number.');
}
var current = document.getElementById('box2');
current.oninvalid = function(e)
{
e.target.setCustomValidity('Please enter a number.');
}
//function parameters do not have types?
function calculateAge(birthYear, currentYear)
{
var a = birthYear.match("^[0-9]+$").length == 1;
var b = currentYear.match("^[0-9]+$").length == 1;
//var check1 = Number.isInteger(birthYear);
//var check2 = Number.isInteger(currentYear);
var page = document.getElementById("content");
// fire off an error message if one of the two fields is NaN.
if (a ==true && b==true)
{
//var page = document.getElementById("content");
var content = page.innerHTML;
var age = currentYear-birthYear;
var stage;
if (age <18)
{
stage = "Teenager";
}
else if (age >= 18 || age <= 35)
{
stage = "Adult";
}
else
{
stage = "Mature Adult";
}
// \n not working at all...why?
var outputMessage = "Your stage is: " + stage + ".\n" + "Your age is: " + age + "." + '\n';
var node = document.createTextNode(outputMessage);
page.insertBefore(node, page.firstChild);
}
else
{
var outputMessage = "Error: please enter a number.";
var node = document.createTextNode(outputMessage);
page.insertBefore(node, page.firstChild);
}
}
var button = document.getElementById("submit");
button.onclick = function()
{
value1 = button.form.box1.value;
value2 = button.form.box2.value;
calculateAge(value1, value2);
}
</script>
</body>
</html>
I tried "adopting" some of the example code for form validation and my code refused to give me a little bubble that says something along the lines of "wrong input!" like the example code on the documentation had, so i decided to go with a simpler approach.
My goal is to check if the inputs from the form fields are number (no letters/symbols), so im doing an if check to do what i want the form result to do (output the stage/age of the person given their info), else I just want it to fire off a generic error message.
However, the error message does not get fired off even if the "age" output is "NaN". for example filling in box1 with a letter and box 2 with a number, you get stage: (blank) age: NaN. What am I missing?
Edit: implemented suggested change, and changed if check condition.

As you said, you have to validate the input first by checking if it is a number, since you cant calculate strings with numbers obviously.
Take a look at Number.isInteger(value), this is what you need. ;)
Here an overview of its outputs:
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger("10"); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false
Edit: [Additions]
Also your code is wrong.
// fire off an error message if one of the two fields is NaN.
if (check1 ==true || check2==true)
isNaN(testValue) returns true if testValue is not a number. So what you do in your code is, you check if check1 OR check2 is not a number and if yes, you continue. I dont think thats what you wanted? Because in the else is your error message, and this else will only be called when both are false (means both of them must be not NaN's and this means you write the error exactly then when all is right)
Correct you should ask, when using IsNaN:
if(check1 == false && check2 == false) {
// Everything okay - No error
} else {
// One of them, or both, is not a number - Print error
}

Related

Showing an image based on a number range in Javascript

I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>
You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

javascript form validation not doing anything

i am trying to ensure an in put the contents of an input field is within an allowable number of character and if it is not print out an error message after the input field. the bellow js is contained in an external js file.
function validateForm()
{
var err_msg = getElementById('feedback_msg_first_name').value;
var first_name = getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}
The basic markup
<script type="text/javascript" language="javascript" src="client_form_val.js"></script>
</head>
<body>
<form id="register" name="register" action="includes/register.inc.php" method="post" onsubmit ="return validateForm();">
<label class="label">First Name:</label> <input type="text" name="first_name" id="first_name" /><br />
<span id="feedback_msg_first_name"></span>
the form is simply submitting without anything happening. where an I going wrong? any help would be appreciated.
Have a look at the following http://jsfiddle.net/VL7dc/2/
Rather than explaining where your going wrong, think you need to try and understand why this works and your doesnt.
function validateForm() {
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2) {
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
} else {
err_msg.innerHTML = '';
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}
You are calling the function when keyup event is fired in form. As a result when a user start typing his/her name after typing a single character this will show the error message.
Instead of calling the function when keyup event is fired, call the function when some button click happens (When the whole first name is typed).
You are forgetting to do document.getElementById. Firebug is giving errors on that
Getting errors:
Uncaught ReferenceError: getElementById is not defined
When you fix the missing documents you get this
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
Reason for the second is this
var err_msg = getElementById('feedback_msg_first_name').value; <-- string
err_msg.innerHTML = 'first name cannot contain less than 2 characters'; <--performing innerHTML on string
Try this
function validateForm()
{
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Trouble with clearing other text boxes when value is backspaced

I am a beginner at Javascript, this is my first Javascript that isn't just 'cut/paste/hack'. I created an calculator that updates the output as input is typed, I can get all my 'answerboxes' to clear when the input box is blurred then focused, but if I backspace the value out of the input box the 'answerboxes' still show the 'answers' based on the last char. value that was backspaced.
In my 'validiateTheInput' funct. I can declare an 'if = "3"' to clear them and it works when a '3' is the value (which would not work in the end :) ), but I can't seem to catch it if the field appears blank do to user backspacing the value from the box.
Am I obsessing over something stupid, or am I just missing something?
Heres the whole thing (with some basic HTML ommitted):
There is also a bit of overkill in the validation function because I was experimenting with trying to catch the 'blank input' do to backspacing.
//jQuery keyup to grab input
$(document).ready(function() {
$('#totalFeet').keyup(function() {
validiateTheInput();
});
});
//clear calculated values
function clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField) {
answerbox.value = "";
answerbox1.value = "";
answerbox2.value = "";
totalFeetField.value = "";
};
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = document.getElementById('totalFeet');
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
// feel like I should be able to catch it here with the length prop.
if (totalFeetField.value.length == 0) {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// if input is usable, do the good stuff...
if (totalFeetField.value != "" && !isNaN(totalFeetField.value)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField.value)) {
alert("The Total Sq. Footage Value must be a number!")
document.getElementById('totalFeet').value = "";
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField.value == '3') {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField.value == 'undefined' || totalFeetField.value === null || totalFeetField.value === '') clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 5.95; // set multiplier
document.getElementById('answerbox').value = answer.toFixed(2);
}
// calc the second box
function calcSecondBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 18.95; // set multiplier
document.getElementById('answerbox1').value = answer.toFixed(2);
}
// calc the third box
function calcThirdBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 25.95; // set multiplier
document.getElementById('answerbox2').value = answer.toFixed(2);
}
HTML:
<div id="calculator">
<form name="calculate">
<label for="total">Total Value to Calculate:</label> &nbsp&nbsp&nbsp&nbsp
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes(totalFeet, answerbox, answerbox1, answerbox2);"><br /><br />
<label for="answerbox">Total Value X $5.95:&nbsp&nbsp&nbsp&nbsp$</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"><br /><br />
<label for="answerbox1">Total Value X $18.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"><br /><br />
<label for="answerbox2">Total Value X $25.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15">
</form>
</div>
The problem is that you're not storing the element objects in variables - you're storing their values:
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
...so later, when you call the following function, passing these variables as an argument:
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
...you're not passing the elements. You can fix it by removing .value off each line in your variable assignments.
Working demo: http://jsfiddle.net/AndyE/Mq6uN/
Side note and shameless plug: if you want something a little more robust than keyup for detecting input, check out this blog post.
You are passing the value of answerbox, answerbox1 etc to the clearBoxes function, not the elements themselves.
Here's a full jQuery approach:
//jQuery keyup to grab input
$(document).ready(function () {
$('input[id$=totalFeet]').keyup(function () {
validiateTheInput();
});
function clearBoxes() {
$('input[id$=answerbox]').val("");
$('input[id$=answerbox1]').val("");
$('input[id$=answerbox2]').val("");
}
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answerbox = $('input[id$=answerbox]').val();
var answerbox1 = $('input[id$=answerbox1]').val();
var answerbox2 = $('input[id$=answerbox2]').val();
// feel like I should be able to catch it here with the length prop.
if (totalFeetField == "") {
clearBoxes();
}
// if input is usable, do the good stuff...
if (totalFeetField != "" && !isNaN(totalFeetField)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField)) {
alert("The Total Sq. Footage Value must be a number!")
$('input[id$=totalFeet]').val("");
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField == '3') {
clearBoxes();
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField == 'undefined' || totalFeetField === null || totalFeetField === '')
clearBoxes();
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 5.95; // set multiplier
$('input[id$=answerbox]').val(answer.toFixed(2));
}
// calc the second box
function calcSecondBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 18.95; // set multiplier
$('input[id$=answerbox1]').val(answer.toFixed(2));
}
// calc the third box
function calcThirdBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 25.95; // set multiplier
$('input[id$=answerbox2]').val(answer.toFixed(2));
}
});
Also, here's the HTML
<form name="calculate" action="">
<label for="total">Total Value to Calculate:</label> &nbsp&nbsp&nbsp&nbsp
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes();"/><br /><br />
<label for="answerbox">Total Value X $5.95:&nbsp&nbsp&nbsp&nbsp$</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"/><br /><br />
<label for="answerbox1">Total Value X $18.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"/><br /><br />
<label for="answerbox2">Total Value X $25.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15"/>
</form>
Sometimes mixing jQuery and plain javascript doesn't work too well. This code should work in clearing your textboxes when the first textbox is empty. It also works on number validation.

Categories

Resources