Jimmy
Jimmy

Reputation: 12487

Focus a field when the enter button is pressed

So i've had a bit of help and I'm nearly there but I was wondering if its possible to have a field focus when I hit enter assuming I'm in a specific field.

This is my code: http://jsfiddle.net/spadez/xT5X5/2/

To get it to focus on the "current" field when I hit enter in an "accepted" field. This can be seen if you first add something, and then click on the field that is added and hit enter. I tried this code without much luck:

$(".accepted").keyup(function(e) {
    if (e.which == 13) {
        $(".current").focus();
    }
});

Also, I was wondering if there is a better way of adding these "enter" commands into my code, because it seems like there could be a better way.

Upvotes: 0

Views: 1157

Answers (3)

aleation
aleation

Reputation: 4844

You need to change the part of code you copied to this:

$('.form').on('keyup', '.accepted', function(e) {
    if (e.which == 13) {
        var line = $(this).parent(); // this targets '.line'
        //this targets line's "container", which is '.copy', then find all the .current's in the next node (.line)
        var current = $(line).parent().next().find('.current');

        //as var current returns a list with all the .current's found, even if there's only one, it returns an array of elements in case there were more, so we select the first one from the array
        current = $(current)[0];
        $(current).focus();
    }
});

Explanation: As .accepted is a class that is created after the document load, it's not existing when you bind the keyup function

You need to use on() instead, targeting '.accepted',

I have split down how to find the '.current' you want so you understand it, but you can reach it in several ways actually. I used the one I thought it would be easier to understand, here is a link to a working fiddle: http://jsfiddle.net/QaHB3/1/

Upvotes: 1

Khanh TO
Khanh TO

Reputation: 48972

Replace

$(".accepted").keyup(function(e) {
    if (e.which == 13) {
        $(".current").focus();
    }
});

with:

$(document).on("keyup",".accepted",function(e) {
    if (e.which == 13) {
         $(this).closest('.copies').next().find(".current").focus();
    }
});

Check demo

Upvotes: 2

LiamB
LiamB

Reputation: 18586

The problem is you are setting up the keyup event on page load and then dynamically creating the textbox's - the result is the textbox's are not bound to any event.

So you have 2 options add onClick="" to the textbox's or move the bind under the creation like so.

http://jsfiddle.net/xT5X5/4/

            $(html).appendTo(container);

            $(".accepted").keyup(function(e) {
                if (e.which == 13) {
                    $(".current").focus();
                    return false;
                }
            });

Upvotes: 1

Related Questions