Burning Hippo
Burning Hippo

Reputation: 805

Focusing to the .next() td textbox in a table row using jQuery

I want to be able to press tab once the .editbox is clicked and it take the focus to the next .editbox. I have been messing with the code for an hour now and cannot "find" the next element.

Here is my code to do it. For help you will likely need more context. I made a jsfiddle to elaborate on what I am dealing with.

//on tab
        $(".edit_tr").on('keydown', '.editbox', function(e) { 
            var keyCode = e.keyCode || e.which; 

            if (keyCode == 9) { 
                e.preventDefault(); 
                var focus = $(document.activeElement);
                //console.log(focus);
                focus.closest('td').siblings('.editbox').focus();
                console.log(focus.parent().next('.editbox'));
            } 
        });

Upvotes: 0

Views: 3366

Answers (2)

dragontrainer
dragontrainer

Reputation: 108

On line #41 you have to go with:

focus.closest('td').next().find(".editbox").show().focus();

This will go back to the current td, look for the following td tag, search for .editbox and before you can focus() on it you have to show() it (make it visible) first.

This solution will only work for 1 line. If you want to move between different lines with the tab key you'll have to do the following:

var nextEditbox = focus.closest('td').next().find(".editbox");
//check if there are still .editboxes on the same line
if(nextEditbox.length){
    //go for it and focus the next edit box on the same line
    nextEditbox.show().focus();
}
else {
    //move to the next line and search for the next editbox
    nextEditbox = focus.closest('tr').next().find(".edit_td:first").find(".editbox");

    //show and focus
    nextEditbox.show().focus();
}

//this will end the focusing and the .change() (which is defined above) will fire and do the ajax
focus.blur(); 

You'll have to do the hiding of the .text elements yourself.

Edit: Here's the Savebutton-Solution. I didn't test it, but I think it should work.

var changes = [];
$(".editbox").change(function(){
   changes.push({ id : $(this).attr("id"), changed : $(this).attr("name"), data : $(this).val() });
});

$(".savebutton").click(function(){
   //AJAX SENDING THE changes VAR TO THE PHP FILE
});

Upvotes: 2

defool
defool

Reputation: 301

It seems that

$(".edit_tr").on('keydown', '.editbox', function(e) { 

Should be

$(".edit_td").on('keydown', '.editbox', function(e) { 

Besides, JQuery editTable may meets your requirements.

Upvotes: 0

Related Questions