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.
I am writing some Javascript/Jquery for a co-worker that is supposed to edit text in a textfield as the user is typing. The purpose of the code is to add formatting to a string of characters (in particular, formatting strings of twelve characters into a valid formatted mac address), however on Firefox I am unable to use the backspace to delete characters once they have been entered into the textfield.
Here is the code that does the formatting:
$(document).ready(function () {
var length = 0;
$("#mac_input").focusin(function (evt) {
$(this).keypress(function () {
content = $(this).val();
content_pre_format = content.replace(/\:/g, '');
content_formatted = content_pre_format.replace(/\n/g, '');
var text_input = $('#mac_input');
if (content_formatted.length % 12 == 0 && length != 0) {
text_input.val(text_input.val() + "\n");
}
length = content_formatted.length % 12;
if (length % 2 == 0 && length != 0) {
if (text_input.val().charAt(text_input.val().length - 1) == ':') {
} else {
text_input.val(text_input.val() + ':');
}
}
});
});
});
Edit: I figured out more about the bug. When I start typing, lets say "abc", right when I type the "c" the script edits the field to show "ab:c". I can backspace the "c" and the ":" but no more. At this point the text field shows "ab", however if I use ctrl-a to select all, the text field changes to "ab:"
here's a more robust solution (current solution will break if a user starts deleting anywhere except the end of the stirng):
$(document).ready(function() {
$("#mac_input").keydown(function (event) {
if (!((event.which > 47 && event.which < 71) || (event.which > 95 && event.which < 106))) {
event.preventDefault();
}
});
$("#mac_input").keyup(function () {
var content=$(this).val();
content = content.replace(/\:/g, '');
content = content.replace(/\n/g, '');
content = content.replace(/(\w{12}(?!$))/g, '$1\n').replace(/(\w{2}(?!\n)(?!$))/g, '$1:')
$(this).val(content);
});
});
it ensures the string is always parsed as a collection of MAC addresses
to explain, it uses to regular expressions,
([abcdef0123456789]{12}(?!$)) matches any sequence of twelve characters that can conform a MAC address and aren't at the end of the string (that's what the (?!$)) lookahead does), and replaces it with the matched string and an appended newline, then it matches any sequence of 2 MAC address characters (([abcdef0123456789]{2}) that aren't immediately followed by a new line or the end of the string ((?!\n)(?!$)).
Just check this: if(event.key == "Backspace") {return;} at the beginning of your keypress handler, and you should be fine.
NB: You have to add the event argument to your keypress handler function.
i tried to count and limit the user inputs from two text fields. that means max char is 20, then user can enter only 20 char in both text fields.I tried like this
$(document).ready( function() {
jQuery.fn.getLength = function(){
var count = 0;
var max=$("#max").val();
this.each(function(){
count += jQuery(this).val().length;
});
var rem=max-count;
return rem;
};
var $inputs= jQuery('#left,#right');
$inputs.bind('keyup',function(){
var remain=$inputs.getLength();
jQuery('#count').html($inputs.getLength());
$("#left").keyup(function(){
if($("#left").val().length > remain){
$("#left").val($("#left").val().substr(0, remain));
}
});
$("#right").keyup(function(){
if($("#right").val().length > remain){
$("#right").val($("#right").val().substr(0, remain));
}
});
});
});
but it only works for single text box, doesn't take values from 2 fields. any help please..
All you need is this code, it detects the keypress in either #left or #right, if the count of the two is more than 20, it removes the last character typed
$("#left,#right").keyup(function () {
var charCount = $('#left').val().length + $('#right').val().length;
if (charCount > 20) {
difference = -Math.abs(charCount - 20);
$(this).val($(this).val().slice(0, difference));
}
});
Demo http://jsfiddle.net/k8nMY/
My first solution worked on keydown and used return false to stop further entry, however this had the effect of disabling backspace and other keys.
This solution, which executes on keyup waits until after the key is pressed then counts characters. If the number is over 20 it will remove the last character typed. This way, the user can still press backspace and make changes as they wish, but not go over 20 chars.
I have also modified the script further, what it does is detect ANY change, e.g. a paste of a long string. It removes the 'difference' above 20 characters.
This should be a complete solution to the problem.
DEMO: http://jsfiddle.net/EEbuJ/2/
JQuery
$('#left, #right').keyup(function(e) {
if (maxLen() <= 20)
{
// Save the value in a custom data attribute
$(this).data('val', $(this).val());
} else {
// over-ride value with saved data
$(this).val($(this).data('val'));
}
});
function maxLen() {
var x = 0;
$('#left, #right').each(function() {
x += $(this).val().length;
});
return x;
};
This will save the typed in value for your inputs to a custom data attribute, if the total number of characters in the specified inputs is no more than 20.
When the maximum number of characters is reached then we stop saving the typed in value and revert the value back to our previous save (i.e. less than the maxiumum) effectively undo-ing the value.
Well it should be easy one: http://jsfiddle.net/4DETE/1/
var textLength =$inputs.eq(0).val().length+$inputs.eq(1).val().length;
if(textLength>=20)
return false
just count length of values, if you'll have more elements to limit, use jquery.each to iterate inputs
I doubt you can do $inputs.getLength() as $inputs is an array and thus will return the arraylength: 2
You will have to add up the overall sign length in both inputs:
$('#left,#right').keydown(function(){
var leftlength = $('#left').val().length;
var rightlength = $('#right').val().length;
if(leftlength + rightlength > 20)
{
return false;
}
});
or to make it shorter
if($('#left').val().length+$('#right').val().length >20){return false;}
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.
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.