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
Related
This question already has answers here:
Throttle event calls in jQuery
(7 answers)
Closed 5 years ago.
I'm working on a live ajax search field. So we have:
<input type="search" id="search">
And I want to trigger the search once the user has stopped typing for 500ms.
I got it working like this:
function throttle(f, delay){
var timer = null;
return function(){
var context = this, args = arguments;
clearTimeout(timer);
timer = window.setTimeout(function(){
f.apply(context, args);
},
delay || 500);
};
}
$('#search').keyup(throttle(function(){
// do ajax
}));
The problem is: if user holds shift key and releases it, the search will trigger regardless. So no new keys are added and the same search term was submitted.
How can I make it so that it triggers only if a new character has been added/removed?
Simply keep track of the state:
var currentSearch = "";
Then whenever a keyup happens, check if the input changed, if not stop updating:
if($("#search").val() === currentSearch) return;
//updated so:
currentSearch = $("#search").val();
Sidenote: as DOM lookup is time intensive you may cache $("#search") ...
You could also use the keyup event, and check if the keycode matches the keys on which you want to act on. Please refer this answer
Adapting that answer to your case:
$('#search').keyup(
function(event) {
var isWordCharacter = event.key.length === 1;
var isBackspaceOrDelete = (event.keyCode == 8 || event.keyCode == 46);
if (isWordCharacter || isBackspaceOrDelete) {
(throttle(function(){
// do ajax
})))();
}
})
You should use input event instead of keyup, which will be triggered only when the value will change.
$('#search').on('input', throttle(function(){
// do ajax
}));
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed. (For input elements with type=checkbox or type=radio, the input event does not fire when a user clicks the control, because the value attribute does not change.)
But be aware that this event has some problems in IE9/10/11 (and is not supported in previous IE versions at all):
[2] IE 9 does not fire an input event when the user deletes characters from an input (e.g. by pressing Backspace or Delete, or using the "Cut" operation).
[3] IE 10 and 11 has a bug, input event fires on placeholder attribute changes.
But the IE10/11 problem is kind of ok, so it depends on if you need to support IE9.
https://developer.mozilla.org/en-US/docs/Web/Events/input
EDIT: unfortunately change is not a suitable solution as it occurres only after blur (loosing focus of the input). Correct solution is to use input event.
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 have a few inputs on my page that need to have a max length of sorts and this is working to an extent except that an extra number keeps being added because of a plugin we're using...and no I can't get rid of the plugin causing it.
To fix this I need to remove one character from the input field. I have gotten to the point where it will remove it from the value of the input, but it is still showing on the screen...which is the issue.
Is there a way to disallow typing after they hit a certain point using JavaScript? I cannot use max length in the case because the virtual keyboard we are using ignores that completely.
I have something like this
var target = event.currentTarget;
var name = $(target).attr("name");
var validationLength = $(target).attr("validation").length;
$('input[name="'+name+'"]').on('keyup keydown change', function () {
if($(this).val().length > validationLength){
$(this).val().substr(0,$(this).val().length-1);
};
});
And like I said this will remove it from the value of the input, but not what the user actually sees on the screen (the most important part). Any help would much appreciated!
validationLength = 10;
$('#test').on('keyup keydown change', function () {
if($(this).val().length > validationLength){
val=$(this).val().substr(0,$(this).val().length-1);
$(this).val(val);
};
});
http://jsfiddle.net/mctkpLph/
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, '');
}
});
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