For loop with user input javascript - javascript

So basically I have a for loop and I am trying to get it to run x amount of times. Depending on what the user inputs. The issue I am having is how to get the user input and also make sure that its a number not any other type of input. making them try again if its wrong.

It's simple really
Input Number : <input id="numberinput" onkeypress="return event.charCode >= 48 && event.charCode <= 57" />
<button id="btn" onclick="doAction()">
Send
</button>
<script>
var doAction = function () {
var input = document.getElementById('numberinput');
var times = parseint(input.value);
for(var i = 0; i < times; i++) {
//do whatever you need to do
}
}
</script>

In HTML5 you can use <input type="number"> to restrict an input to numeric characters only.
For older browsers, that are not HTML5-compatible, use <input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>. This utilizes Javascript to make sure that only numeric input is accepted into the input box.
Check out the snippet below for both solutions in action:
Javascript-based:<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
<br><br>
HTML5 solution (preferred):<input type="number">

Fiddle
HTML
<input type="number" id="myInput">
<button id="myButton">Run Loop</button>
Javascript
$('body').on('click', '#myButton', function() {
var input = $('#myInput').val();
for(var i = 0; i < input; i++) {
alert('You have written inside input field: ' + input + ". This is Alert #" + (i+1))
}
});

To get the value from the input, you can use the value property of the input element.
To make sure the input is a number, you can specify type="number" if HTML5 is supported as mentioned in Angelos Chalaris's answer.
document.getElementById('btn').onclick = function(){
var totalIterations = parseInt(document.getElementById('input').value);
var output = document.getElementById('output');
output.innerHTML = '';
for(var i = 1; i <= totalIterations; i ++) {
var item = document.createElement('div');
item.innerHTML = i;
output.appendChild(item);
}
};
<input id="input" type="number"/>
<input id="btn" type="button" value="Do loop"/>
<div id="output"></div>

Here is an example using user input dialog:
var input, parsedInput = 0;
do {
input = prompt("Please enter valid number", "1");
parsedInput = parseInt(input);
} while(isNaN(parsedInput) || parsedInput < 0);
// keep trying on invalid input or negative number
for( i=0; i< parsedInput ; i++){
console.log("loop " + i);
}

HTML:
<input type="text" name="somefield" id="someid" value="10" />
JS:
var userInput = document.getElementById('someid').value;
if( Number.isInteger(parseInt(userInput)) )
{
// do something
}
Also, Number.isInteger() does not work on Internet explorer 11 or earlier.

Related

A character counter in js?

So I am currently programming my very first website. I am using pure javascript. A part of it will be a comments section - which are stored in a SQL- Database on the server. I want comments to have a maximum length. After searching the web I found this solution. Please do note that this solution is far from perfect.
var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;
i.addEventListener("keydown", count);
function count(e) {
var len = i.value.length;
if (len >= maxchar) {
e.preventDefault();
} else {
c.innerHTML = maxchar - len - 1;
}
}
textarea {
display: block;
width: 200px;
height: 100px;
}
Remaining characters: <span id="count"></span>
<textarea id="textinput">
</textarea>
I found a lot of similar solutions also using jQuery. Now this solution has two major flaws. First it counts the characters before the new character is entered since the registered event is the keydown event - value.length will always give the old count. Secondly once you hit the maximum amount of characters it will prevent all user input - there is no way to delete characters anymore.
Registering the count to keyup doesn't help either - it can't prevent the input of the keydown event.
What is a better solution than this?
So after playing around with it for a bit I came up with this solution. The trick is to split up the count function into two parts - one which counts the characters and one which prevents the user input. Register the preventInput() on keydown, such that the input is prevented before entering, and register the count() on keyup, such that the new value of length is used in the function.
function preventInput(event) {
if (event.target.id == 'commentText')
var maxchar = 255;
else
var maxchar = 20;
//I'm using target here, such that I can use this as a callback for different textfields
var len = event.target.value.length;
var key = event.keyCode || event.which;
//prevent every input apart from UP, DOWN, LEFT, RIGHT and BACKSPACE
if (len >= maxchar && (key != 8 && !(key >= 37 && key <= 40)))
event.preventDefault();
}
function count(event) {
//different lengths for different textfields
if (event.target.id == 'commentText')
var maxchar = 255;
else
var maxchar = 20;
var len = event.target.value.length;
//setting the remaining chars field depending whether Author or Text triggered the event
document.getElementById("remain" + event.target.id.split('comment')[1]).innerHTML = 'Remaining characters:' + (maxchar - len);
//disable the submit button when the user entered too many chars (CTRL + V)
var btn = document.getElementById("submitBtn");
if (len > maxchar)
btn.disabled = true;
else
btn.disabled = false;
}
function setup() {
//setting to events
document.getElementById("commentAuthor").addEventListener("keydown", preventInput);
document.getElementById("commentAuthor").addEventListener("keyup", count);
document.getElementById("commentText").addEventListener("keydown", preventInput);
document.getElementById("commentText").addEventListener("keyup", count);
//initial count
document.getElementById("remainAuthor").innerHTML += 20;
document.getElementById("remainText").innerHTML += 255;
}
.charCounter {
opacity: 0.4;
}
<body onload="setup()">
<form>
<fieldset style="display: inline-block;">
<legend>Submit a comment</legend>
Name:
<input type="text" id="commentAuthor" name="Name:">
<div class="charCounter" id="remainAuthor">Remaining characters:</div>
<textarea name="comment" id="commentText" rows="4" cols="100"></textarea>
<div class="charCounter" id="remainText">Remaining characters:</div>
<br>
<input type="submit" id="submitBtn" value="Submit Comment!">
</fieldset>
</form>
</body>
You can modify the first snipped into something like this
var maxchar = 160;
var i = document.getElementById("commentText");
var c = document.getElementById("remainText");
c.innerHTML = maxchar;
i.addEventListener("keydown", count);
function count(e) {
var len = i.value.length;
len >= maxchar ? i.value = i.value.slice(0,len-1) : c.innerHTML = maxchar - len - 1;
}
<body onload="setup()">
<form>
<fieldset style="display: inline-block;">
<legend>Submit a comment</legend>
Name:
<input type="text" id="commentAuthor" name="Name:">
<div class="charCounter" id="remainAuthor">Remaining characters:</div>
<textarea name="comment" id="commentText" rows="4" cols="100"></textarea>
<div class="charCounter" id="remainText">Remaining characters:</div>
<br>
<input type="submit" id="submitBtn" value="Submit Comment!">
</fieldset>
</form>
</body>

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>

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Count and display number of characters in a textbox using Javascript

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.
You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.
This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.
I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL
Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}
<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation

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