I have an HTML textbox as:
<input style="width: 13%; height: 25%" name="txthour" id="txthour" onkeypress="return isNumberKey(event)">
I want user to stop if they enter a number greater than 12.
When the user has entered 1, I don't want to them to enter the number 3, this will prevent the number becoming 13 (which is greater than 12).
I am dong this in Javascript as:
function isNumberKey(e) {
if (isNaN($("#txthour").val()))
{
alert("Enter only numbers");
}
if ($("#txthour").val() > 12) {
e.cancel;
}
}
But it's not cancelling the text if it enters 13.
Your first problem with your code is that you are binding it on keypress. That means $("#txthour").val() will not be updated before your event.
You need to know which character the user has pressed. There is a function for that: String.fromCharCode();.
To get the current character, you can use this:
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
then you need to check if it is a number:
if(!isNaN(currentChar))
Then you need to concatenate that character to your input:
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
Parse the new value and check if it's less than or equal to 12. If all of these condition matches, return true.
Final code :
function isNumberKey(e) {
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
http://jsfiddle.net/6X9Yq/
Edit
To allow the press of the enter key, you need to check if the keycode is 13 :
function isNumberKey(e) {
if(e.keyCode === 13) return true;
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
Try this instead:
function isNumberKey(e)
{
var exString = $('#txthour').val();
var newString = exString + String.fromCharCode(e.keyCode);
if (isNaN(newString))
{
alert("Enter only numbers");
}
if (newString > 12)
{
e.preventDefault();
}
}
The reason your original code doesn't work is because when the keydown event is called, the value of the text box hasn't been set yet. The code above figures out what the value will be based on your keystroke, and then checks to see if the future value will be > 12. If so, then the preventDefault() call cancels your input.
jQuery solution that:
1) Checks to make sure the user only inputs numbers.
2) Makes sure the number entered is 12 or lower.
3) Alerts the user based on the criteria they're not meeting, and clears the input field.
4) Also accounts for a user pasting something into the field.
$('#txthour').on('paste input', function () {
var number = $(this).val()
if (isNaN(number)) {
alert("Enter only numbers.");
$(this).val('');
}
if (number > 12) {
alert("Value entered must be 12 or lower.");
$(this).val('');
}
});
FIDDLE
$( "#txthour" ).keyup(function() {
if($( "#txthour" ).val() > 12)
{
$( "#txthour" ).val("12");
}
});
http://jsfiddle.net/5tjdL/
The problem:
When the user types a value and you are listening to the onkeypress event, you want to be able to see what the resulting value would be so that you can compare that new value to some other value and then determine if you want to block that input via event.preventDefault() method.
Heres my solution:
1) calculate the "true" new value(now unlike most answers that were previously written that make a huge erroneous assumption "My user will only type a value at the very end of the input field"), I will take into consideration the fact that a user can actually select existing input and overwrite it...ie [before key press] inputField = "12345", user selects "12345" and presses the key for "5", so that would mean that the new value is "5", or if the user selected "234" and pressed the key for "5", the resulting value would be "155".
2) once you have the final "true" value, you can now use the isNaN() method to test if the final value is a valid number or you could just pass the final value to your own method to make whatever comparison you need and decide stop the event by calling event.preventDefault() method. here's a sample code for achieving that.
$(document).keypress(function(event)
{
//this is just a container object for readability purposes
let eventData = {
element: null,
userinput: "",
fieldname: "",
fieldValue: null,
selectionStart: -1,
selectionEnd: -1
}
eventData.fieldName = event.target.id;
eventData.element = document.getElementById(eventData.fieldName);
eventData.fieldValue = element.value; //holds the value before modification
eventData.input = String.fromCharCode(event.keyCode); //what ever the user typed!
eventData.selectionStart = event.target.selectionStart;//this records
eventData.selectionEnd = event.target.selectionEnd;//the user selection if any
let finalValue = getFinalValue(eventData);
if(!isNaN(finalValue)){
//the final value is a number and can be compared to another number!
alert("we have a number! you may proceed");
}else {
//stop right there mister!
alert("You shall not pass!");
event.preventDefault();//user input was blocked!
}
}); // this here marks the end of the onkeypress method,
// and now getFinalValue(eventData) method below...
function getFinalValue(eventData){
let finalValue = eventData.fieldValue.substring(0,eventData.selectionStart) +
eventData.input + eventData.fieldValue.substring(eventData.selectionEnd);
return finalValue;
}//end of the getFinalValue() method
Related
When I type a number it give me e.code of first number that I put and input value empty if i type another number it's give's me e.code of the number but its value is first number value
var input = document.getElementById('w-input');
var kg = document.getElementById('kg');
input.addEventListener('keypress', function (e) {
if (e.code === 'Numpad1'|| e.code==='Numpad2'|| e.code==='Numpad3' ||
e.code==='Numpad4'|| e.code==='Numpad5'|| e.code==='Numpad6'||
e.code==='Numpad7'|| e.code==='Numpad8'|| e.code==='Numpad9'||
e.code==='Numpad0') {
console.log(e.code);
lbsToKg();
}
});
function lbsToKg() {
console.log(input.value);
kg.innerHTML = input.value * 0.45359237;
}
It should get the input value and multiply it with the number but its not multiplying it gives 1-9 number 0 means the value is empty . If i type 12 it gives the 0.45359237 as result means it's multiplying it with 1 not 12
Kamil's answered the question about why the value wasn't correct, but you can also reduce the amount of code you use checking for the pressed key which you might find useful.
var input = document.getElementById('w-input');
var kg = document.getElementById('kg');
input.addEventListener('keyup', function(e) {
// grab the code and the value from the event
const { code, target: { value } } = e;
// if the code is "Numpad" followed by a number call the function
// with the value
if (/Numpad[0-9]/.test(code)) lbsToKg(value);
});
function lbsToKg(value) {
kg.innerHTML = value * 0.45359237;
}
Documentation
Destructuring assignment
RegExp test
keypress is triggered before input change value. Use keyup it is triggered after input change value
function print(inp,e) {
console.log(inp.value);
}
<input onkeypress="print(this,event)" placeholder='keypress'>
<input onkeyup="print(this,event)" placeholder='keyup'>
I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)
This question already has answers here:
HTML text input allow only numeric input
(78 answers)
Closed 6 years ago.
I have a text input for a calculator that is already set up to only accept numbers, and I want to allow for both positive and negative integers, but when the input is used, I want to disallow + and - to be entered. Instead, I want to have those inputs cause operations to be performed.
display.keypress(function() {
if (temp === 0 && $(this).val().isInteger()) {
temp = $(this).val().toString();
} else if ($(this).val().isSafeInteger()) {
temp += $(this).val().toString();
}
});
In order to not allow the user to input anything but numbers, you have to substitute the input's onkeypress event with a function that returns true if the key is valid or false if it isn't. This function is called with a parameter event that has information about the key pressed, so you can read it and check what key was pressed.
But to limit it to numbers and + and - signs it's not enough. You do want your user to be able to delete things inside with backspace and delete, use the arrows and home/end. So you have to consider this as well. So you have to check these keys also.
But this explanation makes it seem more difficult than actually is. I made an example that makes things clearer:
function sumSubtractionFunction(oper) {
console.log(oper);
}
document.getElementById('display').onkeypress = function(event) {
// first we check if + or - were pressed and call the function in that case
if (['+', '-'].indexOf(event.key) > -1) {
sumSubtractionFunction(event.key);
return false;
};
// then we check if the key is one that should be allowed
return ([8, 35, 36, 37, 38, 39, 40, 46].indexOf(event.keyCode) > -1)
|| (Number.isInteger(Number(event.key)));
};
<input type="text" id="display"/>
Key codes:
8 -> backspace
35 -> home
36 -> end
37-40 -> arrows
46 -> delete
This might be the answer:
const isInteger = text => /[+-]?\d+/.test(text)
const data = ['1', '-1', '0.2', '-0,2']
for (let num of data){
console.log(`${num} ${isInteger(num)}`)
}
You can also try this:
const isNumber = text => /[+-]?\d+[,.]?\d*/.test(text)
const data = ['1', '-1', '0.2', '-0,2']
for (let num of data){
console.log(`${num} ${isNumber(num)}`)
}
I think this might be what you are asking for. I set a boolean to see if one of the operators were used, then I strip it out and finally sanitize the input; ready for a function to handle the operation.
var numberInput = document.getElementById('numberInput');
numberInput.addEventListener('input', function(){
var add = false;
var subtract = false;
if(this.value.indexOf('+') >= 0) add = true;
if(this.value.indexOf('-') >= 0) subtract = true;
if(isNaN(this.value.slice(-1))) this.value = this.value.slice(0, -1);
if(add) addOperation();
if(subtract) subtractOperation();
});
function addOperation(){
console.log('add!');
}
function subtractOperation(){
console.log('subtract!');
}
<input type="text" id="numberInput"/>
I do not want to allow to press the function key like (F1,F2..etc),tabular key and also do not add any characters too.
for that one below code which is not working from my site.
document.getElementById("code").addEventListener("keydown",function(e){
var oldOne = this.value;
var newOne = (this.value + String.fromCharCode(e.keyCode)).toLowerCase();
if(oldOne==newOne){
e.preventDefault();
}
document.getElementById('message').innerHTML = "Is it the same: "+(oldOne==newOne)+", Before: "+oldOne+", After: "+newOne;
})
<textarea id="code"></textarea>
<div id="message"></div>
Because convert charcode that is out of available char range [32, 126] would produce a "", while it seems like a empty string, it accounts to length, and can't be trim like a space, so "apple" + "ctrl"' s length is 6 while it displays as "apple", you should better use
if (e.keyCode < 32 || e.keyCode > 126) {
// This is not a valid char, do something to ignore
}
to ignore those special chars, rather than convert it to string, append to current value then compare with oldValue.
When you're writing
String.fromCharCode(e.keyCode)
Then you're always getting a string even if you press though you're not seeing any change in the value, the String.fromCharCode(e.keyCode) is getting something, the string format of the key, it's not a blank string so you're always getting false in the if.
Either you can check in the keycode or you can check after keyup.
keydown event give you the state of object before your character is written.
`keyup events give you the state of object after it's written.
You may want to do something like this (fiddle):
document.getElementById("ta").addEventListener("keydown", function () {
this.oldValue = this.value;
});
document.getElementById("ta").addEventListener("keyup",function(e){
var oldOne = this.oldValue;
var newOne = this.value;
if(oldOne == newOne){
e.preventDefault();
}
document.getElementById('message').innerHTML = "Is it the same: "+(oldOne==newOne)+", Before: "+oldOne+", After: "+newOne;
})
For example we have a textbox which is for tags for a blog. What I want is I want to limit number of tags to be limited.
For instance, "web hosting,php,windows8".
When the user tries to type another one to textbox which he will start with comma, the textbox won't let him write it.
In your keypress handler, capture the event object and do;
if (event.which == 44 && $(this).val().split(",").length > 2) {
event.preventDefault();
}
See it in action here; http://jsfiddle.net/5L7mU/
We can split this problem into 3 smaller problems.
First, we need a way to stop the user from writing stuff into the textbox. When you hook a callback on keypress, the event passed has a method called preventDefault which should do the job. So to block all input:
$("input").keypress(function(event) {
event.preventDefault();
});
Now, to check how many comas there already are in the textbox, we can use regex. The match function will return null instead of an empty array if there are no matches so we gotta check for that.
$("input").keypress(function(event) {
var matches = $(this).val().match(/,/g);
var count = 0;
if (matches)
count = matches.length;
console.log(count);
});
Finally, we need to be able to check if the user typed in a coma. The event objectwill have a property called which that contains the key code of the character entered. With a little bit of exploring, you can find out that the key code for coma is 44.
$("input").keypress(function(event) {
if (event.which == 44)
event.preventDefault();
});
So if we put it all together:
$("input").keypress(function(event) {
var matches = $(this).val().match(/,/g);
var count = 0;
if (matches)
count = matches.length;
if (count >= 2 && event.which == 44)
event.preventDefault();
});
http://jsfiddle.net/4wn5W/
$(document).ready(function(){
$('#textbox').keypress(function(e){
var text = $(this).val();
if(text.split(',').length>3){
return false;
}else if(e.which==44&&text.split(',').length>2){
return false
}
});
});
Fiddle:
http://jsfiddle.net/L4X4C/