Tab keyascii in javascript doesn't work - javascript

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

Related

how do I get javascript function to run on enter key, as opposed to click?

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>

jquery focus first form element on tab of final

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;
}

Keyup event behavior on tab

In this demo, if you place your cursor in the first field and then tab out (without making any changes), the keyup event is fired on the second field. i.e., you are tabbing out of first field and into second field. Is this behavior correct? How can I prevent this from happening? Same applies to shift + tab.
Note:
a) I believe all other keys, printable and non-printable, trigger the keyup event on the first field.
b) The event isn't triggered at all if you keep the tab pressed until it moves out of both fields.
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function() {
$('#firstfield').keyup(function() {
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function() {
alert('Handler for secondfield .keyup() called.');
});
});
A key's default action is performed during the keydown event, so, naturally, by the time keyup propagates, the Tab key has changed the focus to the next field.
You can use:
jQuery(document).ready(function() {
$('#firstfield, #secondfield').on({
"keydown": function(e) {
if (e.which == 9) {
alert("TAB key for " + $(this).attr("id") + " .keydown() called.");
}
},
"keyup": function(e) {
if (e.which != 9) {
alert("Handler for " + $(this).attr("id") + " .keyup() called.");
}
}
});
});
This way, if the Tab key is pressed, you can make any necessary adjustments before handling other keys. See your updated fiddle for an exampe.
Edit
Based on your comment, I revamped the function. The JavaScript ended up being a bit complicated, but I'll do my best to explain. Follow along with the new demo here.
jQuery(document).ready(function() {
(function($) {
$.fn.keyAction = function(theKey) {
return this.each(function() {
if ($(this).hasClass("captureKeys")) {
alert("Handler for " + $(this).attr("id") + " .keyup() called with key "+ theKey + ".");
// KeyCode dependent statements go here.
}
});
};
})(jQuery);
$(".captureKeys").on("keydown", function(e) {
$("*").removeClass("focus");
$(this).addClass("focus");
});
$("body").on("keyup", "*:focus", function(e) {
if (e.which == 9) {
$(".focus.captureKeys").keyAction(e.which);
$("*").removeClass("focus");
}
else {
$(this).keyAction(e.which);
}
});
});
Basically, you give class="captureKeys" to any elements on which you want to monitor keypresses. Look at that second function first: When keydown is fired on one of your captureKeys elements, it's given a dummy class called focus. This is just to keep track of the most recent element to have the focus (I've given .focus a background in the demo as a visual aid). So, no matter what key is pressed, the current element it's pressed over is given the .focus class, as long as it also has .captureKeys.
Next, when keyup is fired anywhere (not just on .captureKeys elements), the function checks to see if it was a tab. If it was, then the focus has already moved on, and the custom .keyAction() function is called on whichever element was the last one to have focus (.focus). If it wasn't a tab, then .keyAction() is called on the current element (but, again, only if it has .captureKeys).
This should achieve the effect you want. You can use the variable theKey in the keyAction() function to keep track of which key was pressed, and act accordingly.
One main caveat to this: if a .captureKeys element is the last element in the DOM, pressing Tab will remove the focus from the document in most browsers, and the keyup event will never fire. This is why I added the dummy link at the bottom of the demo.
This provides a basic framework, so it's up to you to modify it to suit your needs. Hope it helps.
It is expected behavior. If we look at the series of events happening:
Press Tab Key while focus is on first text box
Trigger key down event on first text box
Move focus to second text box
Lift finger off tab key
Keyup event is triggered on second text box
Key up is fired for the second text box because that is where it occurs since the focus was shifted to that input.
You can't prevent this sequence of events from happening, but you could inspect the event to see what key was pressed, and call preventDefault() if it was the tab key.
I was recently dealing with this for a placeholder polyfill. I found that if you want to capture the keyup event in the originating field, you can listen to the keydown event and fire the keyup event if a tab was pressed.
Instead of this:
$(this).on({'keyup': function() {
//run code here
}
});
Change to this:
$(this).on({'keydown': function(e) {
// if tab key pressed - run keyup now
if (e.keyCode == 9) {
$(this).keyup();
e.preventDefault;
}
},
'keyup': function() {
//run code here
}
});
I ended up using this solution:
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function () {
$('#firstfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for secondfield .keyup() called.');
});
});
This solution doesn't run the alert if the key is tab, shift or both.
Solution: http://jsfiddle.net/KtSja/13/

focus() does not seem to work after onblur()

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/

Problem with giving focus to first element inside a container

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.

Categories