How to detect first character of input on keypress() - javascript

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.

Related

Detect entered character with jquery(spanish,áúí)

I'm working on #mention feature and need to load list of users that start with entered character in an input text field .
The problem is with Spanish character like (íáúóé).
in my code I use keypress and keydown to detect characters but in Spanish the keypress event doesn't fire .
in order to type the "á" user need to press two keys
first one is "´" and second is "a" ,then we got "á".
in keydown event using the method String.fromCharCode(e.which || e.keyCode) on this key"´" return "å"
The question how to catch this scenario?
Thanks

Detecting Special Key Presses in Javascript

I have an input box and want to adjust the value when a key is pressed.
'keypress .comment-input': 'onCommentInputKeyBlur',
When a key is pressed, a class is added to the html element to reflect the changes.
onCommentInputKeyBlur: function(ev) {
var $form = $('#comment-submit');
if (ev.which) {
$form.addClass('focused');
} else if (!$(ev.currentTarget).val()) {
$form.removeClass('focused');
}
},
However, this doesn't detect special keys being pressed (ie when a user presses ctrl+v for a paste, it's not detected and the formatting is therefore wrong).
Using keyup and keydown halfway solve the problem, but formatting is wrong for a brief second:
Keydown -> the value isn't supposed to change until an actual value is entered through a keypress, but it changes right when ctrl is hit instead of waiting for the second key
Keyup -> new value is briefly pasted over the previous one while waiting for the key to actually be released.
Is there a better way to about solving this? Ideally, I would like to detect if the key entered does actually produce a value and is not simply a special key.
Look into the onchange event. It is fairly well supported and may solve your problem.
What is the ultimate goal of this functionality? perhaps there is a better approach.
If you insist on doing this via keypress event, then you can simply check event.keyCode and filter out the few keycodes that dont change anything, such as shift, control, alt.

HTML textarea prevent some text from being deleted

I am making a terminal window in HTML/JavaScript and am using a textarea for input. I would like to prevent sections of the text in the textarea from being deleted. For example, if I had the text in the textarea "C:\>Random Code" I would like to prevent the user deleting the "C:\>" text. Is this possible using javascript?
Assuming jQuery, this script will listen for keystrokes, and if any of the required text can't be found (ie: user tries to delete it) it will add itself right back in there:
var requiredText = 'C:>';
$('textarea').on('input',function() {
if (String($(this).val()).indexOf(requiredText) == -1) {
$(this).val(requiredText);
}
}
You cannot make a section of textarea uneditable (only the whole control).
You can use various JavaScript trickery (listening to keypress events and cancelling event using event.preventDefault if the user wants to do something that you do not want to allow)
Another solution is to, instead of having an undeletable section of the input, to automatically append (or prepend ) a predefined string to the user input (and conveneintly display it for the user in some way).
Update:
So, my solution would look like this:
var requiredText = 'C:>';
$('textarea').on('keyup',function(event) {
if (GetSelectionStart(this) < requiredText.length){
event.preventDefault();
event.stopPropagation();
}
}
Where GetSelectionStart is a function that tells the beginning of the selected text (or caret position, if no text range is selected). For some possible implementations, see e. g. Caret position in textarea, in characters from the start
This function assumes that requiredText is always at the beginning of the string. But of course, it can be adapted for more complex scenarios.

JQuery cancel entered text

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.

Jquery Keypress is not working for my input box

$("#epFilter").keypress(function(){
query = $("#epFilter").val();
alert(query);
});
In this code, whenever I type in my text box, it always alert one character less. It doesn't catch the last character. Why?
Use the keyup event instead.
$("#epFilter").keyup(function(){
query = $("#epFilter").val();
alert(query);
});
keypress event is triggered when user presses a key, but before the character is inserted. Use keyup event instead.
Slightly improving Matt's answer (using this inside event handler):
$("#epFilter").keyup(function(){
query = $(this).val();
alert(query);
});
I wonder if that is a "normal" behavior. Shouldn't keypress be similar to keydown+keyup (except for the codes and keys)?
I had the same problem. I have an input-text field and I want to calculate a total on keypress. However, it does not change the total until I input again another character (this means when I entered the first digit it didn't update). I used "keyup" and was "fixed", but I think it could be better if I use keypress as it doesn't fire when I press other keys (like Ctrl, Shift, arrows, etc).
According to the documentation Keypress should work as I expected but for some reason it didn't.
This is not exactly an answer (so don't vote for it). Just my contribution.

Categories

Resources