1

I have this piece of jQuery to detect when the cursor is inside the text box. The idea is to highlight the table row that the text box appears is.

$(".text").on("focus", function() { //do something });

The problem is that this code seems to be registering the tab key inside the text box. The cursor will still move to the next text box when I hit the tab key. However it always insert a tab space into the box as well!!

This is most unexpected and I must admit i'm a little confused by it...

Any help on this matter would be brilliant, thank you.

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
G--
  • 33
  • 4
  • 3
    Can you set up a demo of the problem? That sounds weird. – Evan Davis Dec 17 '14 at 00:01
  • Here is a quick fiddle... http://jsfiddle.net/5cjbcy9o/ - try to 'tab' through the text boxes - it actually inputs a tabspace into the text box – G-- Dec 17 '14 at 00:44
  • It seems to be related to the alert somehow. If I comment out the line with the alert, it doesn't insert tab characters. – AJ Richardson Dec 17 '14 at 01:37

3 Answers3

0

Give every row a tabindex like this
var i=2; $('tr').each($(this).attr('tabindex',i++))

moroccan_dev
  • 310
  • 1
  • 2
  • 11
0

A previous answer has addressed listening to the tab key, by checking the keyCode to see if it matches 9. However, the width of a tab character differs (also reliant on personal preferences), although it is either two or four spaces commonly. Therefore, you can append that white space to the value of the input text when the tab keydown event is detected.

In the following code I have opted to use four white spaces:

$(function () {
    $(".text").on("focus", function () {
        console.log("box selected");
    }).on("keydown", function(e) {
        if ((e.keyCode || e.which) == 9) {
            e.preventDefault();
            $(this).val($(this).val() + "    ");
        }
    });
});

See proof-of-concept fiddle here: http://jsfiddle.net/teddyrised/5cjbcy9o/1/

Community
  • 1
  • 1
Terry
  • 63,248
  • 15
  • 96
  • 118
0

It seems that the alert() you are sending in the focus event is interrupting things in a strange way. You can fix this by setting a brief timeout before sending the alert; that ensures that the alert is sent AFTER the text box receives focus and the tab input has been handled.

setTimeout(function() { alert("box selected"); }, 1);

http://jsfiddle.net/5cjbcy9o/2/

AJ Richardson
  • 6,610
  • 1
  • 49
  • 59