This question already has an answer here:
Keyup event handler shows slow performance
(1 answer)
Closed 5 years ago.
Here is my code:
$('#MyInput').on('keyup', function (e) {
if ($(this).val().length == 1) {
ajaxSearch($(this).val());
}
});
I want to run a function when the input has only one character.
The problem is that if the user type a word really fast, the 'keyup' event seems to be called starting from the second character, which means it will not call ajaxSearch() method.
Is there any way to improve the 'keyup' event speed to call the function when it has only 1 character?
When user types too fast, he/she may have not released the previous key yet, so keyup technically hasn't happened yet.
Try keypress instead of keyup
$('#MyInput').on('keypress', function (e) {
if ($(this).val().length == 1) {
ajaxSearch($(this).val());
}
});
Edit
On keypress input's value property has not be been updated yet, so catch keyup as well in case user only inputs a single character.
$('#MyInput').on('keypress', function (e) {
if ($(this).val().length == 1) {
ajaxSearch($(this).val());
}
});
$('#MyInput').on('keyup keypress', function(e) {
if ($(this).val().length == 1) {
ajaxSearch($(this).val(),e);
}
});
function ajaxSearch(value,e) {
console.log(value, e.type)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="MyInput">
Try keypress instead of keyup
$('#MyInput').on('keypress', function (e) {
if ($(this).val().length == 1) {
ajaxSearch($(this).val());
}
});
Related
This question already has answers here:
How to combine keypress & on click function in JavaScript?
(5 answers)
Closed 5 years ago.
I have the following two functions:
$("input").keypress(function(event) {
if (event.which == 13) {
//code
}
});
$('#login_submit').click(function () {
//code
});
The code which is being used in the functions are EXACTLY the same code, basically code duplication. So i was wondering if there is a way to combine these functions with an AND statement?? There is an question on Stack but it aks for an OR logic. If you want the OR solution here
EDIT: I am trying to make somthing like an explorer. Now I want to hold "shift" and click on an "input" to mark them all. So i need the "onclick" on my input element to be true AND my keydown to be true.
After your edit, I believe what you are looking for is something like the following.
var shift_hold = false;
$(document).keydown(function(e) {
if(e.which === 16) {
shift_hold = true;
}
})
$(document).keyup(function(e) {
if(e.which === 16) {
shift_hold = false();
}
})
$('input').click(function() {
if(shift_hold) {
//your code here
}
})
I want to hold "shift" and click on an "input" to mark them all. So I need the "onclick" on my input element to be true AND my keydown to be true.
Within the click event, you can check if a key is also pressed down (click and key-is-down).
You can use the event object to see which keys are pressed. shift/control/alt have their own explicit properties.
Example:
$("input").click(function() {
console.log(event.shiftKey)
if (event.shiftKey) {
$(this).addClass("selected")
} else {
$(this).removeClass("selected")
}
// could use .toggleClass("selected", event.shiftKey) here,
// shown expanded for clarity
});
.selected {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Shift-click input to select, click to unselect
<input type='text'>
<input type='text'>
I want to capture "enter" and "blur" on a form field. If I hit "enter" and "tab", it will also trigger the blur event... Only one trigger, so "OR" not "AND.
$('#login-input-password').bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
});
answer accepted implemented
FUNCTION usage
function bindTriggerEnterOrBlur(selector,myFunction)
{
$(selector).bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
if (!$(selector).data('has-triggered')) {
$(selector).data('has-triggered', true);
// do something only once, not twice
myFunction();
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
}
});
$(selector).bind('focus', function(e){
$(selector).data('has-triggered', false);
$(selector).select();
});
}
CALL to FUNCTION
bindTriggerEnterOrBlur('#login-input-email',submitLoginEmail);
Where submitLoginEmail is the function that does something for the trigger, e.g.,
function submitLoginEmail()
{
// submit on enter...
var email = $("#login-input-email").val();
if(validEmail(email))
{
submitNextLogin();
}
}
If I am getting your requirement right, you want to execute the callback only once but currently it is getting executed twice.
If that is the case then you will need some way to indicate if the callback has been called already.
One way would be to use data attributes
$('#login-input-password').bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
if (!$(this).data('done') {
$(this).data('done', true);
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
}
});
You will also need another event handler to reset the done attribute of the element
$('#login-input-password').bind('focus', function(e) {
$(this).data('done', false);
});
You are doing an OR. You want a XOR (Exclusive OR), which has to be done using a combination of comparisons.
if (( (e.type == 'blur') && !(e.keyCode == 13)) ||
(!(e.type == 'blur') && (e.keyCode == 13))) {
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
You want to prevent the script from firing again though, so you'll need to do even more state comparison to make sure your asynchronous event handler knows that the blur or keypress events have occurred and ensure the handler doesn't run twice.
You can also do something like:
var doo = function(e){ console.log("do..."); }
$('#wmd-input').bind('blur', doo);
$('#wmd-input').bind('keypress focus', function(e) {
$('#wmd-input').off('blur');
if (e.keyCode == 13) {
doo(e);
} else
$('#wmd-input').bind('blur', doo);
});
And it does bind again when focus happens.
I want to split blur and enter key functions. So I mean that I want jquery to do another function on blur and another on enter key. If enter key was clicked then blur mustn't work, so blur function mustn't execute. This is my jquery code :
$(document).ready(function(){
$("#comment_textarea").on("keypress blur", function(e) {
if(e.type == "keypress" & e.which == 13){
alert("type: "+e.type+"||which: "+e.which);
}
else if(e.type != "keypress" ){
alert("type: "+e.type+"||which: "+e.keycode);
}
});
})
This code alerts two times. First is blur and second is enter click. Have anyone got any ideas.
Thanks.
Since you show an alert the textarea isn't focused anymore, the blur event will be triggered then.
$(function () {
$("#comment_textarea").on("keydown", function (e) {
if (e.keyCode == 13) {
// do your Enter key stuff
e.preventDefault();
}
});
$("#comment_textarea").on("blur", function (e) {
// handle the blur
});
});
Trying to double up probably isn't the best way.
I have a grid with three read-only columns. Whenever user goes in there and try to edit by pressing backspace, I need to alert by giving a message. I am using this script and it doesn't work? Can anyone correct me?
$(document).ready(function () {
$('#txtCode').bind('keypress', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}
});
instead of keypress try with keyup or keydown with .on() method:
$('#txtCode').on('keyup keydown', function (e) {
You can bind multiple events like this too.
and one more thing closing of $('#txtCode') seems to be missing });
$(document).ready(function () {
$('#txtCode').on('keyup keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); //<----");" this is the closing you misssed this
});
See the fiddle in action
If this is all the code you are testing, you weren't closing the function properly, annotated in my posted code. Also use keyup instead of keypress
$(document).ready(function () {
$('#txtCode').bind('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); /*<-- You weren't closing your function properly*/
});
Fiddle
You do indeed need to add a return false statement to ensure the character doesn't get deleted anyway. I also took it a step further and extended jQuery with a preventKeyUsage method.
$(document).ready(function () {
$.fn.preventKeyUsage = function (key, message) {
return this.each(function () {
$(this).on('keydown', function (e) {
return (e.keyCode === key) ? (function () {
alert(message);
return false;
})() : true;
});
});
};
$('#txtCode').preventKeyUsage(8, 'The column is read-only and is not editable');
});
New Fiddle
Working code is:
Java Script Code:
$(document).ready(function () {
$('#txtCode').bind('keypress keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
Here is the updated code
<input type="text" id="txtCode" />
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
return false;
}
});
});
Fiddle Demo
Try this
$(document).ready(function () {
$('#txtCode').on('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
DEMO (Working on Firefox & Chrome)
$('#textbox').keydown(function(event){
if(event.keyCode == 8){
alert("Backspace not allowed..");
return false;
}
});
http://jsfiddle.net/xF9jL/1/
You are missing }); of keypress. google chrome have issues with keypress, u can try keydown instead
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
To use delete ,arrows, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera.
DEMO
You can probably solve the underlying issue by either not using an element that accepts input, or by using the disabled attribute:
<textarea name="example" disabled>Some text</textarea>
If you are posting back to the sever, you should assume the user has edited the field, no matter what you do to prevent it.
keypress event won't give keycodes for all keys in all browsers . Better use keyup or keydown event which gives keycode for all keys in all browsers
In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.
I want to do something when a keypress changes the input of a textbox. I figure the keypress event would be best for this, but how do I know if it caused a change? I need to filter out things like pressing the arrow keys, or modifiers... I don't think hardcoding all the values is the best approach.
So how should I do it?
In most browsers, you can use the HTML5 input event for text-type <input> elements:
$("#testbox").on("input", function() {
alert("Value changed!");
});
This doesn't work in IE < 9, but there is a workaround: the propertychange event.
$("#testbox").on("propertychange", function(e) {
if (e.originalEvent.propertyName == "value") {
alert("Value changed!");
}
});
IE 9 supports both, so in that browser it's better to prefer the standards-based input event. This conveniently fires first, so we can remove the handler for propertychange the first time input fires.
Putting it all together (jsFiddle):
var propertyChangeUnbound = false;
$("#testbox").on("propertychange", function(e) {
if (e.originalEvent.propertyName == "value") {
alert("Value changed!");
}
});
$("#testbox").on("input", function() {
if (!propertyChangeUnbound) {
$("#testbox").unbind("propertychange");
propertyChangeUnbound = true;
}
alert("Value changed!");
});
.change() is what you're after
$("#testbox").keyup(function() {
$(this).blur();
$(this).focus();
$(this).val($(this).val()); // fix for IE putting cursor at beginning of input on focus
}).change(function() {
alert("change fired");
});
This is how I would do it: http://jsfiddle.net/JesseAldridge/Pggpt/1/
$('#input1').keyup(function(){
if($('#input1').val() != $('#input1').attr('prev_val'))
$('#input2').val('change')
else
$('#input2').val('no change')
$('#input1').attr('prev_val', $('#input1').val())
})
I came up with this for autosaving a textarea. It uses a combination of the .keyUp() jQuery method to see if the content has changed. And then I update every 5 seconds because I don't want the form getting submitted every time it's changed!!!!
var savePost = false;
jQuery(document).ready(function() {
setInterval('autoSave()', 5000)
$('input, textarea').keyup(function(){
if (!savePost) {
savePost = true;
}
})
})
function autoSave() {
if (savePost) {
savePost = false;
$('#post_submit, #task_submit').click();
}
}
I know it will fire even if the content hasn't changed but it was easier that hardcoding which keys I didn't want it to work for.