Why it gives me String every time? - javascript

I got input from input tags but whatever I write in inputs it recognize as string value so that I can't use my conditions.
and the second problem if I enter "ddd" for first input and "111" for second input and press button it shows NaN in console. I want to show alert instead of this. How can I correct these?
function addFunc() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
if (typeof x == 'string' || typeof y == 'string') {
var result = parseInt(x) + parseInt(y);
console.log(result);
} else {
alert("Wrong Entry!");
}
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>

The value of an input field will always be a string. Try using isNaN() to determine if the decimal parsed correctly:
function addFunc() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>
Alternatively, if you want to eliminate all bad input (1e would be invalid), try using a + symbol before the string value to convert it to a number. If the string can't be converted, it will return NaN:
function addFunc() {
var x = +document.getElementById("num1").value;
var y = +document.getElementById("num2").value;
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>

Related

Deactivate a button until all javascript conditions have been checked

I´m trying to do different javascript validations before sending a form, the problem is that I haven´t been able to prevent the form from submit, it checks the conditions and sends alerts when a conditions hasn´t been satisfied but it sends the form anyways. I want the button to either be disabled until everything is right or send a message telling user, to check the cuenta.
Thanks in advance. This is my code:
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post">
Enter CLABE account:
<input name="clabe" id="clabe" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control" id="control" maxlength="1" size="2" required >
Again:
<input name="clabe2" id="clabe2" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr>
Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();" >
<hr>
Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="submit" id="myBtn" value="Guardar Cambios" onclick ="return compareclabe();" ><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
<script>
function compareclabe(){
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if( x3 != z3){
alert("keys are not equal");
return false;
}else if (x3 == z3){
this.someFunc(); //I want to call function someFunc and then
if the result is true, execute the next code
if (true){
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
return true;
}
}else{
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x,'37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10 ) {
digito_control = 0;
var dg = digito_control;
}else{
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z){
alert("checkig digit is not equal");
return false;
}
else if (dg == z){
alert("checkig digit is equal");
return true;
}
}
</script>
I changed form submit button type to "button" and if all the validations are passed, then submit form from javascript. See below code
function compareclabe() {
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if (x3 != z3) {
alert("keys are not equal");
return false;
} else if (x3 == z3) {
this.someFunc(); //I want to call function someFunc and then if the result is true, execute the next code
if (true) {
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
$('#form').submit(); //submit form if all validation succeeds
}
} else {
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x, '37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function(a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10) {
digito_control = 0;
var dg = digito_control;
} else {
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z) {
alert("checkig digit is not equal");
return false;
} else if (dg == z) {
alert("checkig digit is equal");
return true;
}
}
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post" id="form"> <!-- I included an id to form -->
Enter CLABE account:
<input name="clabe" id="clabe" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control" id="control" maxlength="1" size="2" required> Again:
<input name="clabe2" id="clabe2" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr> Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();">
<hr> Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="button" id="myBtn" value="Guardar Cambios" onclick="return compareclabe();"><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
But there are many validation plugins where you can easily implement. No need to code from begining. Refer this for an example -> https://jqueryvalidation.org/
You can disable the button by default, and add event listeners to all the inputs in your form. But be weary of other ways to submit the form, like the enter key. I would add an onsubmit function just to prevent all ways the event can happen when you don't want it to.
const form = document.querySelector('form')
const inputs = [...form.querySelectorAll('input')] // convert node list to array
const isValid = () => {
let valid = false
disableButton()
// handle your conditions here
if (valid) enableButton()
return valid;
}
inputs.forEach( input => input.addEventListener('input', isValid))
form.onsubmit = event => if (!isValid()) event.preventDefault()
Or ES5 if you prefer:
var form = document.querySelector('form');
var inputNodes = form.querySelectorAll('input');
var inputs = Array.prototype.call.slice(inputNodes); // convert node list to array
var isValid = function() {
var valid = false;
disableButton();
// handle your conditions here
if (valid) enableButton();
return valid
}
inputs.forEach( function(input) {
input.addEventListener('input', isValid);
});
form.onsubmit = function(event) {
if (!isValid()) event.preventDefault();
};
It's also worth noting that HTML5 has a lot of built-in validation you can take advantage of.

Validate sum of two input fields

I am trying to calculate sum of two fields and validate them. Basically, I need sum of the two input field's value is greater than 100, and want to display a prompt if the sum is less than 100.
So far, I have this:
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<script>
$(document).ready(function(){
var val1 = $("#value1").val();
var val2 = $("#value2").val();
});
</script>
However, I don't know how to validate the result and display a prompt if the sum of these two inputs is less than 100.
Can you please point me in the right direction?
You need to use focusout to get the real-time sum and alert the user if sum is less than 100, You can add keyup events too, but that won't make sense as it would start alerting as soon as you type. IMO, you should have a button, and on click on that button, the calculation and validation shoud be triggered
And if you already have values populated in the input fields, you just need to call / trigger the focusout or click event of the button:
:
$("#value1, #value2").on('focusout', function() {
var value2 = parseInt($("#value2").val()) > 0 ? parseInt($("#value2").val()) : 0;
var value1 = parseInt($("#value1").val()) > 0 ? parseInt($("#value1").val()) : 0
var sumOfValues = value1 + value2;
if (sumOfValues < 100) {
console.log('Your sum is ' + sumOfValues + ' which is less than 100');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
With button:
$("button").on('click', function() {
var value2 = parseInt($("#value2").val()) > 0 ? parseInt($("#value2").val()) : 0;
var value1 = parseInt($("#value1").val()) > 0 ? parseInt($("#value1").val()) : 0
var sumOfValues = value1 + value2;
if (sumOfValues < 100) {
console.log('Your sum is ' + sumOfValues + ' which is less than 100');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<button>Calculate</button>
Wrap your inputs in a form
Add submit button to get values into variables
Write condition logic
Add an output html node to output the result
$(document).ready(function() {
var val1 = parseInt($("#value1").val());
var val2 = parseInt($("#value2").val());
var sum = val1 + val2;
if(sum > 100) {
alert(sum+ ' is greater than 100')
} else {
alert(sum + ' is less than 100')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="input" id="value1" value="70">
<input type="text" class="input" id="value2" value="50">
Check this example.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function myFunction() {
var val1 = $("#value1").val();
var val2 = $("#value2").val();
var sum = parseInt(val1) + parseInt (val2);
if(sum > 100) {
alert('Sum '+sum+ ' is greater than 100')
} else {
alert('Sum '+sum+ ' is less than 100')
}
}
</script>
</head>
<body>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<button type="button" onclick="myFunction()">Check</button>
</body>
</html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<button type="sumbit" name="submit" id="submit">check sum</button>
<p id="resultMessage"></p>
<script>
$(document).ready(function() {
// on button pressed
$('#submit').on('click', function() {
var val1 = $("#value1").val();
var val2 = $("#value2").val();
// numeric validation
if (!isNumeric(val1) || !isNumeric(val2)) {
$('#resultMessage').text('Some field contains not a number');
return;
}
// + operator converts input Strings to Number type
var sum = +val1 + +val2;
if (sum > 100) {
// if sum greather than 100
$('#resultMessage').text('Sum is greather than 100 (' + sum + ')');
} else if (sum < 100) {
// some code if sum less than 100 ...
$('#resultMessage').text('Sum is less than 100 (' + sum + ')');
} else {
// sum is 100
$('#resultMessage').text('Sum equals 100');
}
});
// function for numeric validation
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
</script>
</body>
</html>

Division by zero checking

Doing my calculator...Want to check if my input str has "0" and if it is to alert error. But how not to check "/"? Here it is my function:
<input type="text" name="answer" id="t" onkeyup="isAllowedSymbol(this);checkLength(this);" placeholder="Enter data" >
<input type="button" value=" ÷ " onclick="calculator.answer.value += '/';div(this);checkLength(this);" />
function div(input)
{
var input = document.getElementById("t");
var lastElement = (input.value.length-1);
//alert(input.value.charAt(lastElement));
if (input.value.charAt(lastElement) == 'null')
{
alert(" / to Zero");
}
}
You can use parseInt to evaluate the value of a string.
if (parseInt($("#myInput").val()) > 0) {
// Do something...
}
You can also detect division by zero by using isFinite:
if (isFinite(1/0)) {
// This won't run
} else {
...
}
isFinite will also return false for NaN:
if (isFinite(NaN)) {
// This won't run
} else {
...
}
Instead of using
input.value.charAt(lastElement) == 'null'
in your if statement use
input.value[lastElement-1]+input.value[lastElement] === "/0"
This will check if the last section of the string is zero right after the / sign.
function div(input)
{
var input = document.getElementById("t");
var lastElement = (input.value.length-1);
if (input.value[lastElement-1]+input.value[lastElement] === "/0")
{
alert(" / to Zero");
}
}
<input type="text" name="answer" id="t" placeholder="Enter data" >
<input type="button" value=" ÷ " onclick="div(this);" />
May be it is not full answer but what you can say about this one?
function div(input)
{
var input = document.getElementById("t");
var lastElement = (input.value.length-1);
//alert(input.value[lastElement-1]);
//alert(input.value[lastElement]);
if (input.value[lastElement-1] === "/")
{
if (input.value[lastElement] === "0")
{
alert(" / to Zero");
}
}
}

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

How to check number being entered in textbox dynamically?

i have 5 textbox like
<input type ="text" size="3" name="r"><br>
<input type ="text" size="3" id="1" onchange="vali(this.id)" name="I"><br>
<input type ="text" size="3" name="a"><br>
<input type ="text" size="3" name="s"><br>
<input type ="text" size="3" name="e">
function vali(d){
if(document.getElementById(d).value <0 || document.getElementById(d).value >=30)}
I want user should enter only max 2 digits on each field between 0 & 30. I'm not able to restrict user to enter only 2 digits in field, for example when user enters 151, 15 should come on 1st field and then focus will go on 2nd field automatically and remaining digits will be entered in 2nd field and will be there till the user enters another digit. After entering focus will come on field 3 like this. Also I need to check to each field contain a number between 0 and 30 which I'm checking in above code.
Also when user submit the form all field should be checked for value between (0 to 30) If there is any field present alert bos should pop up else go to next page.i m not able to do this part .this is my form part above the 5 input field
<form name="detail" action ="selectjzone.jsp" onsubmit="return validate(this)">
and edited part is
if (num < 0) {
alert("The value enteres for " +" " + document.getElementById(obj.id).name + " " + "is outside the range0 to 30" );
return false;
} else if (num > 30) {
alert("The value enteres for " +" " + document.getElementById(obj.id).name + " "+ "is outside the range0 to 30" );
return false;
}
return true;
}
Here's a start at how to validate the field and move any extra to the next field:
Working demo here: http://jsfiddle.net/jfriend00/vpTq5/
HTML:
<input id="a" type ="text" size="3" onkeyup="validate(this, 'b')" name="r"><br>
<input id="b" type ="text" size="3" onkeyup="validate(this, 'c')" name="I"><br>
<input id="c" type ="text" size="3" onkeyup="validate(this, 'd')" name="a"><br>
<input id="d" type ="text" size="3" onkeyup="validate(this, 'e')" name="s"><br>
<input id="e" type ="text" size="3" onkeyup="validate(this)" name="e">
Javascript:
function validate(obj, next) {
// fetch value and remove any non-digits
// you could write more code to prevent typing of non-digits
var orig = obj.value;
var mod = orig.replace(/\D/g, "");
var nextObj;
// check length and put excess in next field
if (mod.length > 2) {
// shorten the current value
obj.value = mod.substring(0,2);
if (next) {
// put leftover into following value
var nextObj = document.getElementById(next);
if (!nextObj.value) {
nextObj.value = mod.substring(2);
nextObj.focus();
}
}
} else {
// only set this if necessary to prevent losing cursor position
if (orig != mod) {
obj.value = mod;
}
}
// convert to number and check value of the number
var num = Number(obj.value);
// don't know what you want to do here if the two digit value is out of range
if (num < 0) {
obj.value = "0";
} else if (num > 30) {
obj.value = "30";
}
}
Some notes:
Id values on HTML objects cannot start with a digit. They must start with a letter.
You will have to decide what behavior you want when a number greater than 30 is entered.
Keep in mind that input field values are strings. If you want to treat them like a number, you have to convert them to be numeric.
With more code, you can actually prevent the typing of non-numeric keys and you can move the focus before the 3rd value is typed.
There are ways to get data into fields that does not trigger onkeyup (copy/paste, drag/drop) so you will have to validate at other times too.
If you can use a framework like jQuery, this can be done in a simpler way.
Here is the code for automatic focusing on next field when you keep on typing,
you need to take of validating number between 0 & 30. Hope this helps,
<script>
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function chkEvent(e){
var keyCode = (isNN) ? e.which : e.keyCode;
if(e.shiftKey==1 && keyCode == 9) return false;
if(e.shiftKey==1 || keyCode == 9 || keyCode == 16) return false;
return true;
}
function autoTab(current,to, e) {
var keyCode = (isNN) ? e.which : e.keyCode;
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(current.getAttribute && current.value.length == current.getAttribute("maxlength") && !containsElement(filter,keyCode)) to.focus();
function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length) if(arr[index] == ele) found = true; else index++;
return found;
}
return true;
}
</script>
<input type ="text" size="3" maxlength="2" name="r" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('1'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="1" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('a'), event);}" name="I"><br>
<input type ="text" size="3" maxlength="2" id="a" name="a" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('s'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="s" name="s" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('e'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="e" name="e" >
Here is pure javascript solution is it like what you wanted at all?
http://jsfiddle.net/rfyC8/
Code:
var ieEvents = !!document.attachEvent,
addEvent = ieEvents ? "attachEvent" : "addEventListener",
keyUp = ieEvents ? "onkeyup" : "keyup";
function validator( e ) {
var sib, intValue, val = this.value;
if( val.length >= 2 ) {
intValue = parseInt( val, 10 );
if( isNaN( intValue ) || intValue < 0 || intValue > 30 ) {
this.value = "";
return false;
}
sib = this.nextSibling;
while( sib && sib.className != "textfield" ) {
sib = sib.nextSibling;
}
if( sib ) {
sib.focus();
}
else {
return false;
}
}
}
document.getElementById("textfields")[addEvent]( keyUp,
function(){
var e = arguments[0] || window.event,
target = e.target || e.srcElement;
if( target.className == "textfield" ) {
validator.call( target, e );
}
},
false
);
Use maxlength attribute to limit number of input
maxlength="2"
After settting the above you can use onkeyup event to check the length and change focus
$('#target').keyup(function () {
var maxlength = $(this).attr('maxlength');
if ($(this).val().trim().length == maxlength){
//change focus to next input
//change focus to next input
var inputs = $(this).closest('form').find(':input');
inputs.eq(inputs.index(this) + 1).focus();
}
});

Categories

Resources