Comparing two input fields - javascript

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.

Related

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

Javascript - simple counting

This is my first post and second day with Javascript ;). I try to create a simple form, which:
Allows user put any letter / letters in an input field.
Than I want to send it to my script and:
a) check if anything was given in a form
b) if the user put any sign i want to put it in an array and count up the number of tries
c) if the number of tries reach 10 I want to to stop the script
My script doesn't remeber the number of tries. Moreover, it saves the data in an array but after the script is done it erases everything (I put some console.log() in the script, to see if it does anything). It looks like my variable count doesn't remember the number of tries :(.
How can I fix it ? - but in a simple way of coding :) (I don't want to do a lot of changes in my code)
<script type= "text/javascript">
var given_letters = []; // create an empty array
function givenLetter() {
var count = 0;
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
} else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
</script>
// in BODY section
<div>
<form><p>Put your letter here: <input type="text" id="letter" size="5" required><button onclick="givenLetter();">Send</button></p></form>
</div>
You can use given_letters.length instead of count, less code and its the same value, you need to use e.preventDefault(); so the form doesnt submit the form yet, here its a working example, for e.preventDefault(); to work you need to send the event in the button, like this:
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter(event);">Send</button></p>
</form>
</div>
the JS updated:
var given_letters = []; // create an empty array
function givenLetter(e) {
e.preventDefault();
var max_count = 10;
var letter = document.getElementById('letter').value;
while (given_letters.length <= max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(given_letters.length);//here is your count already
alert("OK");
return true;
}
}
while (given_letters.length === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
The default behaviour of a button in a form is to submit the form... and reload the page (quite stupid, IMO). This is why your script doesn't seem to remember anything. But there's a way to prevent that.
Also, write var count = 0; outside the function, otherwise it's being set to 0 every time the function is called.
var count = 0;
function givenLetter(event) {
event.preventDefault();
// ....
Try this.
Since the button i within the form tag the default behavior of button is submit. so the form will be submitted and reload the page. So to prevent that behavior we use event.preventDefault(); and make count as a global variable.
var given_letters = []; // create an empty array
var count = 0;
function givenLetter() {
event.preventDefault(); //to prevent reloading the page.
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter();">Send</button></p></form>
</div>

Pasting multiple numbers over multiple input fields

I've got a form on my site using 6 input fields. The site visitor simply enters a 6 digit code into these 6 boxes. The thing is that they'll get the 6 digit code and it would be ideal to allow them to simply copy the 6 digit code we send them into these input fields by simply putting pasting into the first input field and having the remaining 5 digits go into the remaining 5 input fields. It would just make it much easier than having to manually enter each digit into each input field.
Here's the code we're currently using, but it can easily be changed to accomplish what is described above:
<input type="text" maxlength="1" class="def-txt-input" name="chars[1]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[2]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[3]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[4]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[5]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[6]">
I saw a posting similar to this here: Pasting of serialnumber over multiple textfields
But it doesn't have the solution I'm looking for. Ideally this could be pulled off using jQuery or plain JavaScript.
Edit
I didn't like the timer solution I used in the paste event and the complexity of just using the input or paste event.
After looking at this for a while I added a solution which uses a hybrid between the 2.
The code seems to do all that is required now.
The Script:
var $inputs = $(".def-txt-input");
var intRegex = /^\d+$/;
// Prevents user from manually entering non-digits.
$inputs.on("input.fromManual", function(){
if(!intRegex.test($(this).val())){
$(this).val("");
}
});
// Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
$inputs.on("paste", function() {
var $this = $(this);
var originalValue = $this.val();
$this.val("");
$this.one("input.fromPaste", function(){
$currentInputBox = $(this);
var pastedValue = $currentInputBox.val();
if (pastedValue.length == 6 && intRegex.test(pastedValue)) {
pasteValues(pastedValue);
}
else {
$this.val(originalValue);
}
$inputs.attr("maxlength", 1);
});
$inputs.attr("maxlength", 6);
});
// Parses the individual digits into the individual boxes.
function pasteValues(element) {
var values = element.split("");
$(values).each(function(index) {
var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
$inputBox.val(values[index])
});
};​
See DEMO
Here is an example of a jquery plugin that does the same thing as the original answer only generalized.
I went to great lengths to modify the original answer ( http://jsfiddle.net/D7jVR/ ) to a jquery plugin and the source code is here: https://github.com/relipse/jquery-pastehopacross/blob/master/jquery.pastehopacross.js
An example of this on jsfiddle is here:
http://jsfiddle.net/D7jVR/111/
The source as of 4-Apr-2013 is below:
/**
* PasteHopAcross jquery plugin
* Paste across multiple inputs plugin,
* inspired by http://jsfiddle.net/D7jVR/
*/
(function ($) {
jQuery.fn.pastehopacross = function(opts){
if (!opts){ opts = {} }
if (!opts.regexRemove){
opts.regexRemove = false;
}
if (!opts.inputs){
opts.inputs = [];
}
if (opts.inputs.length == 0){
//return
return $(this);
}
if (!opts.first_maxlength){
opts.first_maxlength = $(this).attr('maxlength');
if (!opts.first_maxlength){
return $(this);
}
}
$(this).on('paste', function(){
//remove maxlength attribute
$(this).removeAttr('maxlength');
$(this).one("input.fromPaste", function(){
var $firstBox = $(this);
var pastedValue = $(this).val();
if (opts.regexRemove){
pastedValue = pastedValue.replace(opts.regexRemove, "");
}
var str_pv = pastedValue;
$(opts.inputs).each(function(){
var pv = str_pv.split('');
var maxlength;
if ($firstBox.get(0) == this){
maxlength = opts.first_maxlength;
}else{
maxlength = $(this).attr('maxlength');
}
if (maxlength == undefined){
//paste them all!
maxlength = pv.length;
}
//clear the value
$(this).val('');
var nwval = '';
for (var i = 0; i < maxlength; ++i){
if (typeof(pv[i]) != 'undefined'){
nwval += pv[i];
}
}
$(this).val(nwval);
//remove everything from earlier
str_pv = str_pv.substring(maxlength);
});
//restore maxlength attribute
$(this).attr('maxlength', opts.first_maxlength);
});
});
return $(this);
}
})(jQuery);
This shouldn't be too difficult ... add a handler for the paste event on the first input, and then process per the requirement.
Edit
Actually this is much trickier than I thought, because it seems there's no way to get what text was pasted. You might have to kind of hack this functionality in, using something like this (semi-working)... (see the JSFiddle).
$(document).on("input", "input[name^=chars]", function(e) {
// get the text entered
var text = $(this).val();
// if 6 characters were entered, place one in each of the input textboxes
if (text.length == 6) {
for (i=1 ; i<=text.length ; i++) {
$("input[name^=chars]").eq(i-1).val(text[i-1]);
}
}
// otherwise, make sure a maximum of 1 character can be entered
else if (text.length > 1) {
$(this).val(text[0]);
}
});
HTML
<input id="input-1" maxlength="1" type="number" />
<input id="input-2" maxlength="1" type="number" />
<input id="input-3" maxlength="1" type="number" />
<input id="input-4" maxlength="1" type="number" />
jQuery
$("input").bind("paste", function(e){
var pastedData = e.originalEvent.clipboardData.getData('text');
var num_array = [];
num_array = pastedData.toString(10).replace(/\D/g, '0').split('').map(Number); // creates array of numbers
for(var a = 0; a < 4; a++) { // Since I have 4 input boxes to fill in
var pos = a+1;
event.preventDefault();
$('#input-'+pos).val(num_array[a]);
}
});
You're going to have to right some custom code. You may have to remove the maxlength property and use javascript to enforce the limit of one number per input.
As dbasemane suggests, you can listen for a paste event. You can listen to keyup events too to allow the user to type out numbers without having to switch to the next input.
Here is one possible solution:
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.def-txt-input[name="chars['+ (index + 1) +']"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup paste', handleCharacter)
.on('keydown', handleBackspace);
I have this code set up on jsfiddle, so you can take a look at how it runs: http://jsfiddle.net/hallettj/Kcyna/

want alert box to appear if number of buttons selected is less than acquired

I have a grid of buttons which the user can select. What happens is the user enters in the text box the number of buttons they want to select and then they select those buttons in the grid. For example if the user types in "2" in the text box and selects "2" buttons and then tries to select a third, then an alert box appears stating that user is beyond limit please deselect a button.
Now what I want to know is how do I code it so that if user selects less number of buttons than in the text box, then an alert message appears stating to select more buttons?
Thanks
Code in jsfiddle: click here
Well, in order not to be showing an alert every time the user selects a button and it happens to be less than the amount of buttons he/she selected, you'll want to add some sort of submit button and ONLY have a script check the circumstances when they click it.
<form onsubmit="validate.submit(); return false;">
<textarea id="input"></textarea>
<input type="submit" value="Submit" />
</form>
Simple enough, correct? Lets add DIV for where the buttons appear.
<form id="form" onsubmit="validate.submit(); return false;">
<textarea id="input"></textarea> <br />
<div id="buttons"></div> <hr />
<input type="submit" value="Submit" />
</form>
Now lets setup the JavaScript Functionality.
window.validate = ({
config: {
min: 1, // Minimum amount of buttons allowed.
max: 10 // Maximum amount of buttons allowed.
},
data: {
state: 0,
input: null,
buttons: null,
form: null
},
validate: function(refer) {
// Refer is the amount of check boxes checked.
if(refer < this.config.min)
{
alert("You checked to little!");
}
else if(refer > this.config.max)
{
alert("You checked to much!");
}
else
{
alert("You checked JUST right!");
}
},
submit: function() {
if(this.data.state === 1)
{
var refers = this.data.form.val,
refer = 1;
if(Object.prototype.toString.call(refers) === "[object Array]")
{
refer = refers.length;
}
this.validation(refer);
return refer;
}
else
{
this.data.state = 0;
try {
var q = this.data.input.value;
// Use Number object incase of cases where numbers have non-digit,
// characters, like Infinity, NaN, 1e+10, ect.
if(new Number(q).valueOf() === 0 && q.match(/\D/)) { throw new Error(); }
q = eval(q);
if(q > this.config.max)
{
alert("We cannot process that many buttons!");
}
else if(q < this.config.min)
{
alert("You must have at least " + this.config.min + " buttons!");
}
else
{
q = Math.abs(q); // Negative to positive integer.
// Textarea validation complete!
var html = "";
for(var i=q; i>0; i--)
{
html = html + "<input type=\"checkbox\" name=\"val\" />";
}
this.data.buttons.innerHTML = html;
this.data.state = 1;
}
} catch(e) {
alert("You didn't enter a valid Number!");
}
}
},
setup: function() {
window.onload = (function() {
validate.data.form = document.getElementById("form");
validate.data.input = document.getElementById("input");
validate.data.buttons = document.getElementById("buttons");
});
delete this.setup;
return this;
}
}).setup();
This was a quick a dirty example. You might have a few errors, for I didn't test it. Good luck! :D

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