I am trying to get the cursor to jump to focus on the first element of the form. For some reason it keeps getting focus on the 2nd element instead of the first. I did just a simple form.
<form>
<input type="text">
<input type="text">
<input type="text">
<input type="submit" value="Submit">
</form>
$('form').children().keydown(function(e) {
if (e.keyCode == 9 || e.which == 9) {
if ($(this).is(':last-child')) {
$(this).parent().children().first().focus();
}
}
})
Problem
Fiddle
See console logs
when you press tab on last element it focus the 1st element and then perform tab operation so it goes to 2nd element .
Solution
Use event.preventdefault() or return false to stop tab operation .
Working Demo or Working Demo
if ($(this).is(':last-child')) {
$(this).parent().children().first().focus();
e.preventDefault(); // or return false;
}
Related
When I click this button, it runs the function and all is well.
<input id="input_listName" /><button id="btn_createList">add</button>
when I click it, it runs this:
$('#btn_createList').click(function(){
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
});
When I press it, it appends the value in the input to the <li> element.
How do I redo this so that instead of running function on click, the function runs when I click the 'enter key'?
I'd like to hide the submit key all together. Please note, there are no form tags around input and submit, as this is an API app and I'm just trying to filter and not really submit anything.
Don't.
You have a form. Treat it as such.
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listName.value = ""
}, false);
<form id="input_listName">
<input type="text" name="listName" />
<button type="submit">add</button>
</form>
<ul class="ul_current"></ul>
Making it a form provides all of the benefits that a browser does for you. On desktop, you can press Enter to submit it. On mobile, the virtual keyboard may also provide a quick-access submit button. You could even add validation rules like required to the <input /> element, and the browser will handle it all for you.
I think what you want is a check for which key was pressed, correct?
To do that, you simply need to check for
event.keyCode === 13
So your code would be something similar to the following:
$('#btn_createList').keypress(function(event){
if (event.keyCode === 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
Hopefully that does the trick!
With the help of the event, you can catch the pressed enter (keycode = 13) key, as in my example.
Was it necessary?
$('#btn_createList').keypress(function(event){
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
<input id="input_listName" /><button id="btn_createList">add</button> this syntax is technically wrong, your tag is starting with <input> and ending with </button>. Also you can add a simple check to your function that if user haven't entered anything into the input field that should return nothing.
you can also have a look at this cheat sheet to know more about keycodes https://css-tricks.com/snippets/javascript/javascript-keycodes/
$('#btn_createList').keypress(function(event){
if($('#input_listName').val()) {
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
}
});
<div id="btn_createList">
<input id="input_listName" type="text">
<ul class="ul_current">
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
I'm trying to run some specific javascript code when the user hits the tab key to go to the next element on a certain text box. To put this in perspective, this would create a new line of input if the user tabs off of the last element in the row... making it fast to enter lots of List type information.
Html:
<input value="normal tab" />
<input value="normal tab" />
<input value="this tab should fire function when tabbed off of" class="tab-makes-new-row" />
Javascript:
$('.tab-makes-new-row').on('focusout', function (e) {
$(window).keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('I was tabbed!');
}
});
});
Fiddle: https://jsfiddle.net/2cvxqzLt/1/
The problem is, it will fire the alert when tabbing off of any textbox. I want the alert to fire only when tabbing off of the input with the .tab-makes-new-row class. What am I doing wrong? Is it because the textbox is unfocused all the time unless focused?
You're adding an event handler within the handling of an event, and the second one isn't filtered. (It'll also get re-registered multiple times, and won't necessarily fire for the event when the user tabbed out cross-browser.)
Your current approach will be very hard to get right. Instead, I suggest having a small + button just after that input, and adding the row when that + button gets focus. That way, tabbing out of the input will give focus to the + button, and you'll add the new row.
Something along these lines:
var inputs =
'<div>' +
'<input value="normal tab" />' +
'<input value="normal tab" />' +
'<input value="last one" />' +
'<input type="button" value="+" class="new-row" />' +
'</div>';
function addRow() {
// Add the inputs, focus the first one
$(inputs).appendTo("#the-form")
.find("input")[0]
.focus();
}
// Delegated handler for focus on the `+` button
$("#the-form").on("focus", ".new-row", function() {
// Remove the button
$(this).remove();
// Add a new row
addRow();
});
// Add the first row
addRow();
<form id="the-form">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Obviously, you can use CSS to make the button look however you want it to look, but it's useful to have something there to focus — and for the user to see.
You need to combine events to make sure you are monitoring the blur event when the keydown event happens.
$('.tab-makes-new-row').on('keydown blur', function (e) {
if (e.keyCode === 9) {
alert('I was tabbed!');
}
});
Is this the correct solution? It fires when the input gets focused and not unfocused:
I replace $(window) with $(this) so it refers to the input you want.
$('.tab-makes-new-row').keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('I was tabbed!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input value="normal tab" />
<input value="normal tab" />
<input value="this tab should fire function when tabbed off of" class="tab-makes-new-row" />
for example I've 3 elements in my HTML code for text input.
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="text" name="txt3" />
At first load, I set by js to focus in txt1.
My question is, How I can manipulate keyascii when I pressing tab from txt1 to txt3 ?
The fact, I've added some js code with jquery to do that, but doesn't work! It's always focused to txt2. This is my js code:
$('input[name="txt1"]').keyup(function(e){
if((e.keyWhich || e.keyCode) == 9){
$('input[name="txt3"]').focus();
}
});
Listen for keydown and use e.preventDefault() to prevent the default behaviour.
The default behaviour for pressing tab is executed before the keyup event is being fired. That's why you have to use keydown instead.
$('input[name="txt1"]').keydown(function(e){
if((e.keyWhich || e.keyCode) == 9){
e.preventDefault();
$('input[name="txt3"]').focus();
}
});
See this Fiddle
You should listen for keydown instead and be using e.preventDefault()
Example:
$('input[name="txt1"]').keydown(function(e){
if((e.keyWhich || e.keyCode) == 9) {
e.preventDefault();
$('input[name="txt3"]').focus();
}
});
See on JSFiddle
Documentation of preventDefault
I have a list of input fields and when I tab through them I want to loop back to the first one, but it doesn't seem to work.
Here is my HTML
<form id="form">
<input id="mon" type="text"/> Month<br>
<input id="day" type="text"/> Day<br>
<input id="num" type="text"/> Year<br>
<input id="amt" type="text"/> Amount<br>
</form>
and my javascript
window.onload=function(){
$('mon').focus();
$('amt').onblur=function(){
//Process the input fields
$('mon').focus();
}
}
function $(a){return document.getElementById(a)}
I think your onblur event handler is being called before the default handler, causing focus to shift first to input 'mon', then to whatever the browser thinks should be in focus next. Try using the onkeypress event. e.g.
window.onload=function(){
$('mon').focus();
$('amt').onkeydown = function(e) {
//check for IE weirdness
if (e === undefined && event !== undefined)
e = event;
if (e.keyCode == 9) {
$('mon').focus();
return false;
}
}
}
function $(a){return document.getElementById(a)}
Edit: onkeydown actually seems to work in more browsers
Edit 2: added IE case. IE doesn't always pass the event as an argument
For the cursor to appear on the first input box, you need to assign the value of the input box to itself (hack). Also you need to "return false" to stop the event propagation. The modified blur function is below,
<input id="mon" type="text" onfocus="this.value=this.value;" />
$('amt').onblur = function(){ $('mon').focus(); return false; }
Take a look at this fiddle. I think this is what you want to achieve.
http://jsfiddle.net/CucuIonel/7Fpu3/7/
I am just trying to cycle the focus between elements inside a particular element when the tab key is pressed. What I want to do is not to set focus to any element which is not a descendant of an element when tab is pressed from the last control inside the element. At that time the focus must be set to the first input element inside the container.
I have done a sample and it its not working, and I am unable to figure out the issue.
Sample can be found here
The complete code is
Script
$(function(){
$(":input:last","#div1").bind("keydown", function(e){
if ( e.keyCode === 9 )
{
var firstElem = $(":input:first","#div1");
firstElem.focus();
}
});
});
CSS
input.red { width: 200px; border: solid 1px red; }
input { width: 200px; }
HTML
<input type="text" class="red" />
<div id="div1">
<input type="text" id="txt1" />
<select id="sel1">
<option>1</option>
</select>
<input type="text" id="txt2" />
</div>
Any help would be appreciated.
Thanks
Edit
Thanks everyone. Problem solved. It was the lack of a return false; statement in the keydown event.
Try Keypress instead of Keydown
Also return false so that the keypress normal handling is cancelled.
What appears to be happening is that you are moving the focus then the tab happens, moving it to the select. You need to setfocus, then return false so that the regular tab is cancelled.
$(function(){
$(":input:last","#div1").bind("keydown", function(e){
if ( e.keyCode === 9 )
{
var firstElem = $(":input:first","#div1");
firstElem.focus();
return false;
}
});
});
Your example is not working because you are not stopping the keystroke, you set the focus on the first element, and then the tab key is sent, which causes the focus to be changed to the second element.
Try:
$(function(){
$(":input:last","#div1").bind("keydown", function(e){
if ( e.keyCode === 9 ) {
var firstElem = $(":input:first","#div1");
firstElem.focus();
e.preventDefault(); // or return false;
}
});
});
Check the above example here.
Can you not just use the tabindex attribute in the html?
If your page is dynamic it might be easier to set this attribute using JS rather than capturing the keypress etc.