Autotab input with javascript - javascript

I have 3 inputs that need to tab to the next when the max length are reached.
These 3 inputs come with values and when the user change the value of the first input it focus on the next and so on.
My problem is that since my second input has already the length it jumps to the third input. If the use input the values slowly it don't do this.
The source of the problem is that if the typing is too fast the first keyup event is fired after the second type and it fires on the second input.
I've written a jsfiddle with the problem and this is my function to wire the auto focus change.
function WireAutoTab(CurrentElement, NextElement) {
CurrentElement.keyup(function (e) {
//Retrieve which key was pressed.
var KeyID = (window.event) ? event.keyCode : e.keyCode;
var FieldLength = CurrentElement.attr('maxlength');
//If the user has filled the textbox to the given length and
//the user just pressed a number or letter, then move the
//cursor to the next element in the tab sequence.
if (CurrentElement.val().length >= FieldLength && ((KeyID >= 48 && KeyID <= 90) || (KeyID >= 96 && KeyID <= 105)))
NextElement.focus();
});
}
Is there any other event that I can use to prevent this? The behavior that I want is that even if the second input has value, it stops on it.

Related

Entering Extended Latin characters Alt+0256-0383 in a Javascript form

Users of my Javascript data entry popup are unable to enter Extended Latin characters above 255. For instance Alt+0321 is the Polish Ł. Even on this StackOverflow form, I cannot key the character in but can copy-paste it. Whereas ß can be keyed directly because it is Alt+0223.
Is there a way round this limitation? Non-Javascript tools, such as MS Office, work. I'm having to advise people to do data entry in Word, then copy-paste, which is not a good look. Gmail and Google Search seem to be similarly limited.
After long search with no results, here's my solution:
(works for 0-65535 | 0000-ffff)
var altCapture = null;
function keydown(event) {
var keyCode = event.keyCode;
if(keyCode == 18) altCapture = "";
if(altCapture != null && keyCode != 18)
altCapture += (keyCode - 96);
}
function keyup(event) {
if(event.keyCode == 18) {
event.target.value += String.fromCharCode(+altCapture);
}
}
function keypress(event) {
if(altCapture != null) {
event.preventDefault();
altCapture = null;
}
}
<input
onkeydown ="keydown (event)"
onkeyup ="keyup (event)"
onkeypress ="keypress(event)"
>
<input
onkeydown ="keydown (event)"
onkeyup ="keyup (event)"
onkeypress ="keypress(event)"
>
key press is executed after all key ups.
key down 18 (alt), starts capture by setting altCapture to "" from null.
key down not 18 and capturing, appends digit to altCapture.
(key down not 18 and not capturing, default.)
key up 18, appends char from code altCapture (the + converts string to number).
(key up not 18, default.)
keypress and capturing, prevent default and reset altCapture to null.
(keypress and not capturing, default.)

Javascript--tab key not working

I have a javascript program that, in part, poses a division problem and asks for the quotient and remainder to be inserted in two different textboxes. The program in this instance looks like this:
!(C:\Users\Owen Walker\Dropbox (Personal)\Sebzo javascript\quotient_remainder.JPG)
For some reason--the program is fairly complicated--when both textboxes are visible, the user cannot Tab and Shift+Tab from one textbox to the other.
I have therefore written two functions: handleTabInQuotientTextbox() and handleShiftTabInRemainderTextbox(), that, when called in onkeyup from the quotient and remainder textboxes, set the focus on the other textbox. In other words, they do the right thing when Tab is pressed in the quotient textbox, i.e., the caret goes to the reminder textbox, and vice versa when the Shift+Tab keys are pressed in the remainder textbox. What's wrong is that one can no longer enter numbers or other text into the two textboxes.
Here is the code for the two functions:
function handleTabInQuotientTextbox(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode == 9 && tentative_game_chosen == 'rd') {
document.getElementById("user_input_for_remainder_div").focus();
}
return false;
}
function handleShiftTabInRemainderTextbox(evt) {
var e = event || evt; // for trans-browser compatibility
if(e.shiftKey && event.keyCode == 9 && tentative_game_chosen == 'rd') {
document.getElementById("user_input_div").focus();
}
return false;
}
What am I doing wrong?
Any thoughts would be much appreciated.

Move up by UP key from textarea jquery

In html form we need to move up or down using arrow keys to shift focus in the fields. following code works fine for all input elements. but in case of textarea there could be multiple lines so, if we move up or down cursor moves up or down in the textarea itself.
Now, I'm not getting how to move up the focus, if the cursor reaches in the first line of the textarea while pressing up arrow OR move down the focus if the cursor reaches at the end or in the last line of the textarea while pressing down arrow key.
Here is my partial code:
var INPUT_SELECTOR = ':input:enabled:visible';
var inputs = $(INPUT_SELECTOR)
$("form").on("keypress", "input", function(event){
// i is current input
if(event.keyCode === 38){ //action == 'up'
inp = inputs[i > 0 ? parseInt(i) - 1 : inputs.length - 1];
}
if(event.keyCode === 40){ //action == 'down'
inp = inputs[i < inputs.length - 1 ? parseInt(i) + 1 : 0];
}
// focus on the input
moveFocusTo(inp);
});
Our requirement for the up and down arrow keys is same as tab and shift+tab behaviour. everything is done, we have just stuck at textarea.
Sounds like you need to use
https://developer.mozilla.org/en-US/docs/Web/API/event.relatedTarget#1003983
event.relatedTarget
Then you can check to see during the event what element the user is focused on and act accordingly.

JavaScript to accept only numbers between 0 to 255 range

My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
(a < 48) || (a > 57)
for invalid values. So I would change those:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
Pattern usage example you could fetch here:
http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle
http://jsfiddle.net/Indias/P3Uwg/
Single Integer
You can use the following solution to check if the user input for a single integer is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
});
<input id="example" type="text" placeholder="Enter IP address" />
You need to validate the current value of the input, rather than the last key that was pressed:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
A function like this should do it:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
Update
I've set up a fiddle that does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there. Secondly, you're checking key after key, but at no point are you checking the actual value that your input field is getting. There are a few more things, like the use of the onkeypress html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}​
Now this code still needs a lot of work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead.
So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1, which will become 129. This is because 29 * 10 = 290, which already exceed 255, preventing user from entering 129, which is valid. The start position is particularly hard to track when the input type="number". But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.

Change div value based on textbox value using jQuery

I created this fiddle that the div value changes based on your dropdown list selection. http://jsfiddle.net/qSkZW/20/
I want to take it one step further and this is to create a textbox field that if you add for example the number 2 it will change the div value to 240 (in real the 120 you find in the script it will be a php var). If it writes 3 then to 360.
Additionally there must be two limitations.
Prevent them from using non-numeric characters.
The maximum number is pre-configured (from a php variable). Like if the max value is set to 10, if the user writes 30 it will return to 10.
Thank you for your help.
Okay, so first, create a textfield (example id="textfield"), then modify your listener's action to
$("#quantity").change(function () {
var price = parseInt($(this).val(), 10)*120
$("#textfield").attr('value="'+price+'"');
# sets the default value of #textfield to the selection from #quantity
})
.change()
$("#textfield").blur(function () {
# when the element looses focus (they click/tab somewhere else)
var valid = /^\d{2}$/;
# this means any 2 numbers. change {2} to {3} or however many digits.
# you can also also use d[0-10] to identify a range of numbers.
if ( $(this).text() != valid ) {
$("#message").text("Only numbers please!");
$("#message").fadeIn();
# add <span id="message" style="display:none;"></span> next to #textfield
# enclose #textfield & #message in the same element (like <li> or <div>)
}
else {
$("#message").fadeOut();
}
});
Could you please provide more info about #2 (I don't have a clear understanding of what is supposed to happen)
Quick question: why are you trying to put a price in an editable element?
This will do it: http://jsfiddle.net/ebiewener/pBeM8/
You bind the keydown event to the input box in order to prevent the undesired characters from being entered, and bind the keyup event in order check the value & modify the div's height.
$('input').keydown(function(e){
if(!(e.which >= 48 && e.which <=58) && e.which !== 8 && e.which !== 46 && e.which !== 37 && e.which !== 39){ //prevent anything other than numeric characters, backspace, delete, and left & right arrows
return false;
}
})
.keyup(function(){
val = $(this).val();
if(val > 10){
val = 10;
$(this).val(10);
}
$('div').height(val * 10);
});
var max = 30;
$('input').keyup(function() {
var v = $(this).val();
v = isNaN(v)?'':v;
v = v > max ? max : v;
$(this).val(v);
$('div').html(v * 120);
});
http://jsfiddle.net/vWf2x/2/

Categories