I need to bind the 'enter' key on the keyboard to a specific javascript method, but ONLY when a certain text field is in focus.
<input id="post" type="text" style="width:400px;"/>
How would I do this?
I know you can do it with forms and stuff that have a submit action, but can I just bind the 'enter' key to a specific function when this above input field is in focus?
$("#post").focus(function() {
$(this).data("hasfocus", true);
});
$("#post").blur(function() {
$(this).data("hasfocus", false);
});
$(document.body).keyup(function(ev) {
// 13 is ENTER
if (ev.which === 13 && $("#post").data("hasfocus")) {
...
}
});
I recommend you instead bind the the ENTER keyup event on your $("#post") input directly rather then listening for the event on the entire page.
Just bind the onkeyup event to the input in question. You don't need to worry about checking focus at all, because by definition that input will only receive keyup events when it has focus.
I assume JQuery is OK since you included the tag in your question, so within your document ready handler do something like this:
$("#IDforyourcontrol").keyup(function(ev) {
// 13 is ENTER
if (ev.which === 13 && /*whatever other conditions you care about*/) {
// do something
}
});
Related
I have a keypress event listener on an input field to confirm a password. I want the button on the page to be disabled until the password and confirm-password fields have matching values. I am using the .keypress() jQuery function, but it seems to always be one character behind what I expect it to be?
Here is the code
$('#confirm').keypress(function() {
console.log('#confirm').val();
if($('#password').val() == $('#confirm').val()) {
$('button').removeProp('disabled');
console.log("yes");
} else {
console.log("no");
}
});
But when I inspect element and look at the console window on my page, the first time the event is fired it prints the form value as blank. Then when I enter a second character, it prints only the first, and when I type a third character it prints the first two, etc.
For example, if I put asd into the password field and begin typing the same into the confirm field the output will look like this:
<blank>
no
a
no
as
no
So at this point both password and confirm fields have "asd", but I need to enter an extra character before that is recognized and the "disabled" property is removed from the button.
I have tried using .change() instead of .keypress() but that doesn't fire until the input field loses focus, which is not what I want.
I want the button on the page to be disabled until the password and confirm-password fields have matching values
If this is your goal, you can add event listeners to both inputs that call a validation function:
$('#password').on("input", function() { validatePassword(); });
$('#confirm').on("input", function() { validatePassword(); });
function validatePassword() {
if($('#password').val() && $('#confirm').val() && $('#password').val() == $('#confirm').val()) {
$('button').prop('disabled', false);
} else {
$('button').prop('disabled', true);
}
}
It also may be worthwhile adding an ID to the button. Using 'button' would enable/disable all elements on the page.
Example: https://jsfiddle.net/doL4t9vv/1/
I had the same problem few months ago.
Try to use the keyup function from Jquery.
Keypress event is fired when you press the key, so the input is not fill yet.
Keyup event is fired when you release the key.
Can use input event and simplify this down to
var $passwords =$('#confirm, #password').on('input', function() {
var thisValue = this.value.trim();
// does this input have value and does it match other
var isValid = thisValue && thisValue === $passwords.not(this).val().trim();
// boolean used for disabled property
$('button').prop('disabled', !isValid);
});
I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?
I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode
This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.
The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo
This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo
How would I run a check after a keypress function to see if an inputs value was empty so I can do another action.
For example.
$("input[name=amount]").keypress(function() {
$("table[name=apply]").show();
});
I want to hide the table if the user deletes all the keystrokes.
$("input[name=amount]").keyup(function() {
if (this.value == '') {
$("table[name=apply]").hide();
} else {
$("table[name=apply]").show();
}
});
You will probably want to use either the keyup or change event so the value of the text-box has changed before the event handler runs. The keypress event fires before the value of the input has changed, so for instance if the input is blank and a key is entered, the value in the event handler would still read as blank.
Here is a demo: http://jsfiddle.net/jasper/C5KPq/
Use the keyup() method to perform the check after the keystroke has finished:
$("input[name=amount]").keyup(function() {
if(this.value === ''){....}
});
If you bind to the keypress or keydown events, the value of the input inside your event handler will not yet have been affected by the keystroke. This is why you need to bind to keyup instead.
You can try this using keyup event instead of keypress because keypress will not give you the latest value.
$("input[name=amount]").keyup(function() {
//Here this points to the textbox element and value gives its content
if(this.value == ''){
$("table[name=apply]").show();
}
});
If you want to toggle the table the you can use this.
$("input[name=amount]").keyup(function() {
$("table[name=apply]").toggle(this.value != '');
});
toggle(showOrHide) - Display or hide the matched elements.
Demo
you can use the following
if( $(this).val() == "")
try:
if ($("input[name=amount]").val() == '') // input is empty
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.
<input type="text" id="name" onchange="checkLength(this.value)" />
----onchange does not fire on changing contents of name, but only fires when name goes out of focus.
Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.
I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?
(function () {
var oldVal;
$('#name').on('change textInput input', function () {
var val = this.value;
if (val !== oldVal) {
oldVal = val;
checkLength(val);
}
});
}());
This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.
http://jsfiddle.net/katspaugh/xqeDj/
References:
textInput — a W3C DOM Level 3 event type. http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents
A user agent must dispatch this event when one or more characters have
been entered. These characters may originate from a variety of
sources, e.g., characters resulting from a key being pressed or
released on a keyboard device, from the processing of an input method
editor, or resulting from a voice command. Where a “paste” operation
generates a simple sequence of characters, i.e., a text passage
without any structure or style information, this event type should be
generated as well.
input — an HTML5 event type.
Fired at controls when the user changes the value
Firefox, Chrome, IE9 and other modern browsers support it.
This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.
It took me 30 minutes to find it, but this is working in June 2019.
<input type="text" id="myInput" oninput="myFunction()">
and if you want to add an event listener programmatically in js
inputElement.addEventListener("input", event => {})
As an extention to katspaugh's answer, here's a way to do it for multiple elements using a css class.
$('.myclass').each(function(){
$(this).attr('oldval',$(this).val());
});
$('.myclass').on('change keypress paste focus textInput input',function(){
var val = $(this).val();
if(val != $(this).attr('oldval') ){
$(this).attr('oldval',val);
checkLength($(this).val());
}
});
Do it the jQuery way:
<input type="text" id="name" name="name"/>
$('#name').keyup(function() {
alert('Content length has changed to: '+$(this).val().length);
});
You can use onkeyup
<input id="name" onkeyup="checkLength(this.value)" />
You would have to use a combination of onkeyup and onclick (or onmouseup) if you want to catch every possibility.
<input id="name" onkeyup="checkLength(this.value)" onmouseup="checkLength(this.value)" />
Here is another solution I develop for the same problem. However I use many input boxes so I keep old value as an user-defined attribute of the elements itself: "data-value". Using jQuery it is so easy to manage.
$(document).delegate('.filterBox', 'keyup', { self: this }, function (e) {
var self = e.data.self;
if (e.keyCode == 13) {
e.preventDefault();
$(this).attr('data-value', $(this).val());
self.filterBy(this, true)
}
else if (e.keyCode == 27) {
$(this).val('');
$(this).attr('data-value', '');
self.filterBy(this, true)
}
else {
if ($(this).attr('data-value') != $(this).val()) {
$(this).attr('data-value', $(this).val());
self.filterBy(this);
}
}
});
here is, I used 5-6 input boxes have class 'filterBox',
I make filterBy method run only if data-value is different than its own value.
i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />