How do I put focus on a textbox with JavaScript(Or jQuery)?
I have a textbox on a page and after the user presses the enter key, the textbox loses focus. (Keep in mind that no post occurs, the page does not refresh)
I want to be able set the focus back inside of the textbox through javascript so that the user can continue typing and doesn't have to click on anything.
I tried adding the following code after the users has pressed the enter key:
$(".focus").focus();
The code for my textbox:
<input type="text" class="focus" />
but alas, the cursor does not appear inside of the textbox and the user still has to click to continue typing.
How do I fix this problem?
You have to apply the focus code to the input, if the page hasn't loaded or the DOM isn't ready when the code runs, then there's no input yet to focus on..
So you have to check that the DOM is loaded, like this:
$(function(){
$(".focus").focus();
});
http://jsfiddle.net/c7aUS/
You can also include the code at the bottom of the page, before the </body> tag, so that it loads right after all your HTML.
note: If you're running this in jsfiddle, by default your code is run on page load. When using JQuery, it automatically wraps it in this code:
$(window).load(function(){
//your code here
});
EDIT:
In that case, meetamit is very helpful, I think you're looking for this:
$(function(){
$(".focus").focus();
$(".focus").on('keydown', function(event) {
if(event.which == 13) {// Enter key pressed
$this = $(this);
$this.focus();
var value = $this.val();
$this.val(''); /* clear the field */
// do stuff with the value
}
});
});
http://jsfiddle.net/c7aUS/1/
Why does pressing the enter key take away the focus from the field? (I couldn't reproduce it.) It might suggest that there's a hidden problem still. Maybe not. If not, this might help:
$(".focus").on('keydown', function(event) {
if(event.which == 13) {// Enter key pressed
event.preventDefault();
}
});
Related
I have a HTML Forumlar which is processed with ajax. This means it loads the page again not to the process Forumlar. My problem is that when he submits the form by pressing enter the pointer loaded in the input field, which I do not want to. does anyone know how I can prevent this?
$(function(){
$("#myForm input").keypress(function(e){
if(e.keyCode == 13)
e.preventDefault();
});
});
I use the following code to add the selected div value into a input.
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
$('.del').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val(function(index, text){
return text.replace(/(\s+)?.$/, '');
});
})
below is a sample image if the input panel I have! This is developed for a touch device and hence the key pad.
The script works fine to add value on each button press in the keypad. The problem I'm facing is for the room number I want to run an ajax call after the user has entered the amount. But since the focus is removed every button click, how can I run the script when the focus is changed to another input. I tried the jquery .focusout() method but it gets fired each and every time the user clicks on a number button.
if anyone can suggest me a work around that would be a great help!
thank you!
Perhaps you could delay the request with something like the following:
var roomNoChanged = false;
$('#room-number').change(function() {
roomNoChanged = true;
});
$('#table-number, #no-of-guests').focus(function() {
if(roomNoChanged) {
roomNoChanged = false;
$.post(...)
}
});
I had some weird result from jquery events, though I am not fully convinced whether it is a jquery issue. I hope some jquery geeks can answer this.
I had the following code snippet in my html page, to change the focus to the second input box once user enter a string of length 9 in first input box. This auto-focusing is working smoothly. But when I press tab from first input box, it is always skipping the second input box and goes to the next html element to second input box.
$("input.first").change(function (e){
var text = $(this).val();
if (text.length == 9){
$("input[id='second']").focus();
}
});
I tried putting tabindex property to html elements still it continued its misbehavior. But at the end when I changed change event to keypress event tab key started to flow as expected.
Is there anyone who could explain why this happens? Thanks for any answers.
you can add tab index to controls manually. I hope it will work.
$(function() {
var tabindex = 1;
$('input').each(function() {
if (this.type != "hidden") {
var $input = $(this);
$input.attr("tabindex", tabindex);
tabindex++;
}
});
});
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" />
I have some text inputs which I'm validating when a user tabs to the next one. I would like the focus to stay on a problematic input after showing an alert. I can't seem to nail down the correct syntax to have JQuery do this. Instead the following code shows the alert then focuses on the next text input. How can I prevent tabbing to the next element after showing an alert?
$('input.IosOverrideTextBox').bind({
blur: function(e) {
var val = $(this).val();
if (val.length == 0) return;
var pval = parseTicks(val);
if (isNaN(pval) || pval == 0.0) {
alert("Invalid override: " + val);
return false;
}
},
focus: function() {
$(this).select();
}
});
I don't like forced focus, but can't you just focus after the blur takes place?
element.focus();
If doing that in the blur event doesn't always work (I'm not sure exactly when it fires, before or after the actual blur takes place), a redundant timeout will do, as well: setTimeout(function () { element.focus() }, 0).
But please don't do this. Heck, you should never be using alert or any kind of modal dialog for a web interface, either. How about adding a invalid class to the form field, putting a message off to the side of it, and disabling submit until all fields are valid? That's a much less invasive solution that allows me to fill out the form in whatever way is best for me, rather than whatever way is simplest for you.
You can do this with the validation plugin by default.
focusInvalid default: true
Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
Then you'd only need to have the focus event handler do your select and let the plugin handle validation.