I would like to catch an event that some text was entered to a TextBox and modify it BEFORE user sees the change.
I tried adding the keyDown, keyUp and keyPressed events, but they are all called after the change.
Is there a way to do that?
This has to work
$("#input").keypress(function(replace){
if(replace.which==46)
{
$("#input").val($(this).val() + 'no_dots');
replace.preventDefault();
}
});
It replaces (,) characters, try this code I think it keypress works well
This seems to be what you're after. http://jsfiddle.net/wcS9j/1/
var blacklist = /(foo|bar)/ig;
$('input').on('keyup', function () {
if (blacklist.test(this.value)) {
this.value = this.value.replace(blacklist, '');
}
});
Related
I have a little problem with validating an input field.
Here is my validation code:
_validateInput: function(e) {
var value = e.currentTarget.value;
var key = e.which || e.keyCode;
var re = /[^0-9\.]/gi;
if (re.test(value + String.fromCharCode(key))) {
return value;
} else {
return value + String.fromCharCode(key);
}
},
The logic is the next. If user input non-digital characters, the function return current value of the input, without the last symbol.
If user type digit or dot, function return current input value + entered number.
What is my problem:
1) It not allows user to enter dot.
2) String.fromCharCode for dot character returns "¾" symbol.
3) Special symbols like backspace, tab, etc... doesn`t work.
4) Commands like Ctrl+V, Ctrl+A also does not work
Could someone help me to solve this problems? What is wrong with my RegEx?
Thanks!
P.S. Function fired on the keydown event
Unless you need to support older browsers listen for oninput instead of onkeydown and a lot of the processing will have been done for you.
http://www.w3schools.com/jsref/event_oninput.asp
This event is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed. The other difference is that the onchange event also works on <keygen> and <select> elements.
Whenever oninput is triggered then check the value in the text area is valid and if it isn't then correct it. This will also let you check for multiple dots being entered (if you need to do that). For example 231.21.23 is not a valid number.
I'm working on a script for our client's project that autotabs you onto the next input field when you've hit the maximum character count for a particular input. For some reason the input value is returning one less than it should be, and therefore tabs to the 'next' input when an extra character is entered above the 'threshold'.
Here's my script to watch the inputs value - ofc, if there is a better way please advise :) -
var watchLength = function (watch) {
watch.onkeypress = function () {
var nextInput = getNextSibling(this);
console.log(this.getAttribute('data-autotab-length'));
console.log(this.value.length);
if (this.value.length == this.getAttribute('data-autotab-length')) {
nextInput.focus();
console.log('Limit reached here');
}
};
};
And a jsFiddle to the working input. The first input is limited to '2' characters, but when you type in 3 it jumps to the next input. I think this is something to do with the keypress/keydown event not reading the initial value, but I'm at a loss of how to fix it. Any help really appreciated.
I'm logging the results in the Console:
http://jsfiddle.net/qdnCZ/
The Problem is, that onkeypress will fire before you want it to. You can simply replace onkeypress by onkeyup, that way you make sure that the <input> elements value is set correctly the time you check it.
See: http://jsfiddle.net/qdnCZ/1/
Yes it will return one less, simply use +1 on the length check. This is beacuse onkeypress event is executed before the field is updated, which means using e.preventDefault() the letter will not appear in the field. You could use onkeyup otherwise.
Use onkeyup instead onkeypress
onkeyup gets fired after field gets updated
if (this.value.length == this.getAttribute('data-autotab-length')) {
nextInput.focus();
console.log('Limit reached here');
return false; // this is prevent the third value being entered
}
Updated fiddle
How can I detect if the value of a textarea changes using jQuery? I'm currently using keyup() but this triggers every key stroke of course, I dont want my code to run if it's an arrow key that was pressed or any other key that doesn't have an impact on the value of the textarea.
Take a look:
$('textarea').keyup(function() {
if (content was changed)
// Do something
});
I hope you understand. How can I do this the best way? I don't want to compare the current value to an old value to check for changes, I hope that's not the only way.
By all means the easiest way is to store old values to data and do the check every keyup. The solution is quite short and will work in any case. No need to reinvent the wheel.
$("textarea").data("oldValue", function() {
return this.value;
}).keyup(function() {
var $this = $(this);
if (this.value !== $this.data("oldValue")) {
// Do something
$this.data("oldValue", this.value);
}
});
DEMO: http://jsfiddle.net/vvbSj/
$('textarea').blur(function() {
//This will be invoked when the focus is removed
});
$('textarea').change(function() {
//Same as the blur
});
Is this what you want
So I'm doing character counting on a text field. I need to update the character count on keypress (not keyup). The issue is that with jquery's .keydown() method, it refreshes the counter before the character is entered, so the counter is always 1 keypress behind the actual count. How can I get the count to change on keypress, but wait for the character to be entered?
Thanks!
setTimeout seems to work here:
$('input').keydown(function(e) {
var $this = $(this);
setTimeout(function() {
var text = $this.val();
console.log(text.length);
}, 0);
});
Use .keyup() instead. It's triggered when the key is released, so the counter will increment then.
From the documentation:
The keyup event is sent to an element when the user releases a key on
the keyboard. It can be attached to any element, but the event is only
sent to the element that has the focus.
You use it in the same way you would any other event:
$('input').keyup(function(e) {
var text = $(this).val();
console.log(text.length);
});
Make sure to count the number of characters in the text box (as in the example above), not the number of keys pressed. For example, pressing Ctrl + C would result in two extra characters counted, but none actually entered into the input.
If you're using jQuery 1.7+, use .on():
$('input').on('keyup', function(e) {
// Do your magic
});
A simple example:
var MAX_CHARACTERS = 60;
$('textarea').bind('keyup keydown', function() {
var $element = $(this);
if($element.val().length > MAX_CHARACTERS) {
$element.val($element.val().substring(0, MAX_CHARACTERS));
}
$('.counter').val(MAX_CHARACTERS - $element.val().length);
});
demo
I need to change in a text input the character '.' to ',' while typing.
In IE I change the keyCode event property in the keypress event, like this
document.getElementById('mytext').onkeypress =
function (evt) {
var e = evt || window.event;
if (e.keyCode && e.keyCode==46)
e.keyCode = 44;
else if (e.which && e.which==46) {
e.which = 44;
}
};
but it seemes that in Firefox it's impossible to change characters typed in key events.
Any suggestions?
Try this. It works on all browsers:
window.onload = function () {
var input = document.getElementById("mytext");
input.onkeypress = function () {
var evt = arguments[0] || event;
var char = String.fromCharCode(evt.which || evt.keyCode);
// Is it a period?
if (char == ".") {
// Replace it with a comma
input.value += ",";
// Cancel the original event
evt.cancelBubble = true;
return false;
}
}
};
Update: Pier Luigi pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.
The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.
Assume that all properties in an Event object are immutable. The DOM spec doesn't address what happens when you change those values manually.
Here's the logic you need: listen for all key events. If it's a period, suppress the event, and manually add the comma at the cursor position. (Here's a code snippet for inserting arbitrary text at the cursor position.)
You'd suppress the event in Firefox by calling event.preventDefault(); this tells the browser not to go ahead with the default action associated with this event (in this case, typing the character). You'd suppress the event in IE by setting event.returnValue to false.
If it's not a period, return early from your handler.
Technically you just want to replace all dots with commas.
document.getElementById('mytext').onkeyup = function(){
this.value = this.value.replace('.', ',');
}
If I look at the official Document Object Model Events document, mouse events fields are defined as read-only. Keyboard events are not defined there, I suppose Mozilla followed this policy for them.
So basically, unless there is some smart trick, you cannot alter an event the way you want. You probably have to intercept the key and insert the char (raw or translated) where the caret is, the way JS HTML editors do.
Does this really need to be done on the fly? If you are collecting the information to be posted to a form or submitted to a database, would it not be better to modify the data once it was submitted? That way the user never sees the confusing change.
This is possible now by intercepting and cancelling the default keydown event and using HTMLInputElement.setRangeText to insert your desired character. This would look something like this:
document.addEventListener('keydown', $event => {
if($event.code === 'Period'){
$event.preventDefault();
let inputEl = document.querySelector("#my-input");
inputEl.setRangeText(
',',
inputEl.selectionStart,
inputEl.selectionEnd,
"end"
);
}
})
setRangeText will insert text at the cursor position in a given input. The "end" string as the last argument sets the cursor to the end of the inserted content.
More info here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText