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.
Related
Using any browser that isn't a mobile device, number input has many features of changing it besides typing a number into it:
-Pressing Up on the arrow keys increases the value, and down arrow keys decreases it. If held down, it will increase or decrease by step, default at 1 (integer) rapidly. Additionally, on most browsers, when selecting it will show two additional buttons to the right to increment and decrement it (and holding down those as well will increase/decrease rapidly):
However, this only works with decimal numbers. There isn't a method of having a field to enter, say hex numbers. There exist a text version (<input type="text">) that allows the user to enter any character in it, and a JavaScript can parse the text into a number (or bigint) using regex prior conversion. But that will not behave like a number since it is a “general-purpose” text input.
So my question is, how do I make an input, that is a text, to behave like a number but accepts a given radix (I don't know the code, but it reacts to up/down, and features increase/decrease, and can be held down for continuous change)? Having the ability to increase/decrease a hex number would be great for making HTML that does things that are programmer-like stuff such as color math or something related to software data.
Solved (but partially). Here is a template, this only works with bigint unless you edit it to support number (double-precision floating point). I don't think the up and down arrow to the right of the input is even possible:
<input type="text" id="tester" class="HexInput"><br>
<input type="text" id="tester2" class="HexInput"><br>
<input type="text" id="tester2" class="SomethingElse"><br>
<script>
window.onload = function(){
var FocusedElement = document.activeElement;
if(FocusedElement.addEventListener ) {
FocusedElement.addEventListener('keydown',this.keyHandler,false);
} else if(FocusedElement.attachEvent ) {
FocusedElement.attachEvent('onkeydown',this.keyHandler);
}
}
function keyHandler(e) {
if (((e.keyCode == 38)||e.keyCode == 40)&&(document.activeElement.className == "HexInput")) {
var target;
var InputNumber = BigInt(CorrectHexBigIntValue(document.activeElement.value))
if (!e) var e = window.event;
if (e.target) target = e.target;
else if (e.srcElement) target = e.srcElement;
if(e.keyCode == 38) {
InputNumber++
} else if(e.keyCode == 40) {
if (InputNumber > 0n) {
InputNumber--
}
}
document.activeElement.value = InputNumber.toString(16).toUpperCase()
}
}
function CorrectHexBigIntValue(String) {
if ((/^([0-9]|[A-F]|[a-f])+$/).test(String) == false) {
String = 0n
}
return CanConvertHexStringToBigInt = BigInt("0x" + String)
}
</script>
But there is one problem: Pressing up always brings the caret (blinking text cursor) to the beginning of the line. On a number input, this always bring the caret to the end, on both pressing up and down.
YES! It is solved. Sorry for adding another answer, stackoverflow is having a bug that wouldn't let me add more text in the previous post. This here is meant to include an improved version, I found a way to prevent the caret from going to the beginning of the line by using preventDefault():
<input type="text" id="tester" class="HexNumberInput" onchange="code()"><br>
<input type="text" id="tester2" class="HexNumberInput" onchange="code()"><br>
<input type="text" id="tester3" class="somethingelse" onchange="code()"><br>
<script>
window.onload = function(){
var FocusedElement = document.activeElement;
if(FocusedElement.addEventListener ) {
FocusedElement.addEventListener('keydown',this.keyHandler,false);
} else if(FocusedElement.attachEvent ) {
FocusedElement.attachEvent('onkeydown',this.keyHandler);
}
}
function keyHandler(e) {
if (((e.keyCode == 38)||e.keyCode == 40)&&(document.activeElement.className == "HexNumberInput")) {
var target;
var InputNumber = BigInt(CorrectHexBigIntValue(document.activeElement.value))
if (!e) var e = window.event;
if (e.target) target = e.target;
else if (e.srcElement) target = e.srcElement;
if(e.keyCode == 38) {
InputNumber++
e.preventDefault() //Prevents the caret (blinking text cursor) from being placed at the beginning of the line.
} else if(e.keyCode == 40) {
if (InputNumber > 0n) {
InputNumber--
}
}
document.activeElement.value = InputNumber.toString(16).toUpperCase()
document.activeElement.setSelectionRange(document.activeElement.value.length, document.activeElement.value.length)
}
}
function code() {
var b = 1 + 1
}
function CorrectHexBigIntValue(String) {
//This converts the user's input hex string (negative numbers not allowed)
//to BigInt.
if ((/^([0-9]|[A-F]|[a-f])+$/).test(String) == false) {
String = 0n
}
return CanConvertHexStringToBigInt = BigInt("0x" + String)
}
</script>
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.
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/
Is it possible to change the character which has been entered on keypress, without doing it manually?
For example, if I want to force uppercase letters based on some condition, it'd be nice to do the following:
function onKeypressHandler(e)
{
if ( condition )
{
e.which -= 32;
}
}
But of course that doesn't work.
NOTE: This is not an across the board uppercasing, but only specific characters.
Maybe I want to say if ( e.which >= 97 && e.which <= 102 ) or if ( Wind.Direction == 'South' ) or whatever - the condition itself is not important, but the uppercasing must only apply to the current character not the entire input.
I can do it by manually appending the changed character, but this is an ugly and messy way of doing it, and probably slower than it could be.
function onKeypressHandler(e)
{
if ( condition )
{
$j(this).val( $j(this).val() + String.fromCharCode( e.which - 32 ) );
return false;
}
}
A specific flaw with this method - if selecting all input text and entering a key, if it drops into this then it doesn't remove existing content, but simply appends to the content the user wanted removed. (Would need to investigating detecting any selected text to solve that, which makes this one even uglier.)
Can anyone provide a better solution?
The following will do the job. It's based on an answer I wrote to another question. Customize the transformTypedChar function to suit your needs; my example capitalizes only the letters a-g.
If you need this on a textarea rather than an <input type="text"> then be aware that there are issues in IE <= 8 with line breaks that the following code doesn't handle for the sake of brevity. You can find the cross browser function for obtaining the selection within a textarea here: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
function transformTypedChar(charStr) {
return /[a-g]/.test(charStr) ? charStr.toUpperCase() : charStr;
}
document.getElementById("your_input_id").onkeypress = function(evt) {
var val = this.value;
evt = evt || window.event;
// Ensure we only handle printable keys, excluding enter and space
var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
if (charCode && charCode > 32) {
var keyChar = String.fromCharCode(charCode);
// Transform typed character
var mappedChar = transformTypedChar(keyChar);
var start, end;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
// Non-IE browsers and IE 9
start = this.selectionStart;
end = this.selectionEnd;
this.value = val.slice(0, start) + mappedChar + val.slice(end);
// Move the caret
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
// For IE up to version 8
var selectionRange = document.selection.createRange();
var textInputRange = this.createTextRange();
var precedingRange = this.createTextRange();
var bookmark = selectionRange.getBookmark();
textInputRange.moveToBookmark(bookmark);
precedingRange.setEndPoint("EndToStart", textInputRange);
start = precedingRange.text.length;
end = start + selectionRange.text.length;
this.value = val.slice(0, start) + mappedChar + val.slice(end);
start++;
// Move the caret
textInputRange = this.createTextRange();
textInputRange.collapse(true);
textInputRange.move("character", start - (this.value.slice(0, start).split("\r\n").length - 1));
textInputRange.select();
}
return false;
}
};
How about preventing default action and then triggering the keypress? Something like,
function onKeypressHandler(e)
{
if ( condition )
{
e.preventDefault();
// create new event object (you may clone current e)
var ne = new jQuery.Event("keypress");
ne.which = e.which - 32;
$(e.target).trigger(ne); // you may have to invoke with setTimeout
}
}
You've got to see this.. I was pretty happy with myself after getting it to work..
You obviously would want to include sufficient criteria to avoid going into a loop here.
The code below returns false when condition evaluates to true, but it fires the same event with a different charCode which will not return false.
document.getElementById("input1").onkeypress = Handler;
function Handler(e)
{
e = e || window.event;
if ( e.charCode == 97 )
{
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress",true, true, window, false, false,false, false, 0, e.charCode -32);
this.dispatchEvent(evt);
return false;
}
return true;
}
you could use fireEvent in IE...
I used
http://help.dottoro.com/ljrinokx.php
and
https://developer.mozilla.org/en/DOM/event.initKeyEvent for reference
Not really sure what you want but will this work?
$('#my_element').keyup(function(){ $(this).val().toUpperCase(); });
or use a sub string to get the last character pressed and do toUpperCase() on that?
(psst... you can use keydown or keypress too).
Can you use css?
<input type="text" style="text-transform: uppercase;" />
Peter,
You might find some inspiration here:
http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML15/jsdhtml15-05.htm
basically walks around the various ways to look at the keypress events and functions around that 'area'.