When typing into a <input type="text"> field I would like to precheck every entered value before it appears on the screen. E.g. if the user enters any non numeric value, nothing will happen and only if he enters a numeric value the field will change.
Which is the right event to use keydown(), keyup() or is there something better? How do I cancel the current change of the text field without having to remember the old value and manually resetting it?
You could bind to the keypress event and then check the character represented by the which property of the event object. If it isn't a number you can use preventDefault to prevent the default behaviour of writing the character to the element:
$("#someInput").keypress(function(e) {
if(isNaN(String.fromCharCode(e.which))) {
e.preventDefault();
}
});
Here's a working example.
Related
I'm using jquery's function keypress for my input field
Now, let's say that I want to know when the user types a letter, if this is the first character in the field. I now use something like:
element.keypress(function(e){
//...
if(elementValue.length()==0){
//Do something
}
}
The problem is when the user selects the text that typed and then presses a key (lets say for the character 'A') that replaces it. Then this code returns the length of the old-(soon to be replaced) text.
I know that I could use keyup instead, but I think I need to stay with keypress because I have to do some checks for the pressed physical keys. (this answer really shows the difference between keyup and keypress in this case)
Any suggestions?
User Paul S. put me in the right direction...
That's what I have now and it works:
element.keypress(function(e){
//...
if(this.selectionStart==0){
//Do something
}
}
This way I detect when a key has been pressed while the caret was just at the beginning of the field.
I am making a small calculator (just for JavaScript learning) and I have two input fields for fraction calculation:
Field: numerator
Field: denominator
And a button "Calculate fraction" which executes the function myFraction(numerator,denominator) when user clicks on it.
Is it possible to do the same without the Button?
I mean JavaScript should recognize that someone is making input and then calculate the fraction automatically.
You can hook into the onkeyup or onkeydown event handlers and call your function:
<input type="text" id="numerator" onkeyup="myFraction()" />
<input type="text" id="denominator" onkeyup="myFraction()" />
You'll need to grab the values of the text boxes inside the myFraction() function and check to see if they're blank before you output the fraction value to the screen though.
function myFraction() {
if(document.getElementById("numerator").value != "" &&
document.getElementById("denominator").value != "") {
...do calculations
}
}
Sure, I think you need onChange() (as the text is being edited) or onBlur() (when the textbox looses focus). See the difference here.
Since you're studying, jQuery can help with some of the nuances - including here.
Javascript is event driven, so yes, you can catch the event after they are typing with keyup or when the user moves off from a textbox control.
You could check the length of a textbox after they leave it, validate what they entered and then run the calculation.
I usually use blur to catch after a user leaves a textbox. I usually use Onchange for select.
I have an input element with an onchange event. The onchange event alerts the user if the value is not accepted, and returns focus back to the input element.
However, if the user then clicks out of the element, the onchange event doesn't fire - which is understandable since the user hasn't made a further change, but it introduces the problem of only validating once.
I explored a possible solution to reset the value back to what it was before it was changed, but I'd like to avoid that if at all possible for the sake of allowing the user to correct the value they entered without having to type the whole thing again.
Another possibility was to put the validation into the blur event but this would introduce other problems such as events on other elements firing if they are focused.
So my question is, if the user changes the input value from 'X' to 'Y', can I return focus to the element, leaving the value as 'Y' but make it treat 'X' as the pre-change value, thus behaving so if the user changes it back to 'X' the change event will not subsequently fire, but if they leave it as 'Y' and lose focus again, the change event fires again as if changing from 'X' to 'Y'?
Why not just mark the field as invalid (using CSS or jQuery to add markup) instead of using an alert? The field remains invalid until the user changes the value to a valid one, and the validation script removes the invalid marking.
Is the input type text? In these circumstances I prefer to use onkeyup instead of onchange for the very reason you're describing.
Sometimes even that doesn't work: This will not capture the change when text is pasted into the text box using a mouse since a key isn't pressed (but shift+insert or ctrl+v are). You might want to add the same event to both onchange and onkeyup to cover all bases.
I want to know get text box value when I type the value by every key press.
I have to get the value.
If I type numbers I have to get, so I have checking with that value.
var my_input = document.getElementById('my_input');
my_input.onkeyup = function() {
alert(my_input.value);
}
<input type='text' id='my_input' />
Probably you will have to serve events on input field: onkeypress, onkeyup, onkeydown, onpaste, onchange.
You can get the value of an input element from its value property, e.g.
element.value
To execute some function on every key press, you should bind an event handler for the keyup event to this element.
You should make yourself familiar with event handling in JavaScript and the variations in the different browsers. The site I linked to (quirksmode.org) is a very good resource for that.
One thing to note is that in certain browsers the method by which you get the value of a textarea differs. I'm thinking in IE6, at least, it actually registers the value of a textarea as it's innerHTML (or the other way around).
Worth doing a check in you eventListener for if the value is set, or not, and checking the innerHTML if it's not, just in case!
Here's the problem, in abstract terms: i have three input fields (A, B, C). two of them need to be text inputs (A and B), the third is of irrelevant type. I need to enable the third if A is not empty and B is not empty. I need to disable C if A is empty or B is empty.
The code
// empty is the empty function from the phpjs project
// framework used: jQuery
// A, B and C are classes here
$(".A, .B").keypress(function(){
if( !empty($(".A").val()) && !empty($(".B").val()) )
$(".C").attr("disabled","");
else
$(".C").removeAttr("disabled");
});
I want to be able to check this on keypress, but when requesting the value of the input that is edited when the keypress event occurs i get the value that was calculated before the keypress event.
Has anybody stumbled upon this before and solved it?
have you tried using the keyUp event?
Use the keyup event instead.
Attach your handler to the keyrelease event. The value should have been updated by then.
use a combination of handlers for keyup and change. the keyup handler will update as the user types (excepting edge cases like holding a key down, which doesn't seem like a concern here) and the change handler will catch things like the user cutting the text with mouse actions before they can switch to field C. as an added measure you could add verification on field C's focus event, to make sure A and B really have something.
$('.A, .B').keydown(function(event) {
if(!empty($('.A').val()) && !empty($('.B').val()))
$(".C").attr("disabled","");
else
$(".C").removeAttr("disabled");
});
At the keypress event, the value of the INPUT is not yet set. Hence you can't easily know if it is empty.
While the keyup fires, the value of the INPUT is set.
But things get worse. The user can empty the field with the mouse or the Edit menu of the browser. In that case keyup is not fired.
In our web app we auto-save the values. Like in Mac OS, if you know, there is almost no save buttons.
To allow a reaction here is more or less what we do:
onfocus: a setInterval starts polling every 120ms or so, and checks the input for any change
if there is a change do the relevant action
onblur: a clearInterval stop the polling