Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Focus out on TR

Okay, so I'm making a plugin to allow inline editing of tables in my website, going great so far, I've got most of it done, but I can't seem to get Focusing out of the table right. So if someone is done editing and starts editing a new row or just clicks out of the row, it should save and go back to normal. But if I use blur on the row, there's no response, but if I use blur on the element, it triggers when people swap from one element to another

But if I use focusout on the row, it triggers whenever someone leaves the element as well, even if they click in the same row. Nor is there anything under the event variable that tell me what element it's setting the focus on, so I can't compare with the current row to see if they're just clicking with in the row.

I'm thinking of having it save on Enter/Mouse Click to a Save button/Start editing another row, but I'd rather get this to work, as it seems to be a much better method of doing it. Thought anyone? Please?

like image 599
Gareth Parker Avatar asked Oct 10 '22 07:10

Gareth Parker


2 Answers

I would handle your request by binding a click handler for the whole document, and then adding a stopPropagation() call within my other click events. I've setup a fiddle to demonstrate: http://jsfiddle.net/NwftK/

<table border="1" width="200">
    <tr id="myRow"><td>Hello</td><td>World</td></tr>
</table>

And the jQuery:

$(function () {
    $("#myRow").on('click', function (e) {
       $(this).css('background-color', 'blue');
        e.stopPropagation();
    }); 

    $(document).on('click', function () {

       $("#myRow").css('background-color', 'red');
    });

});
like image 162
Jake Feasel Avatar answered Oct 13 '22 11:10

Jake Feasel


The problem is that even if you have nested elements, focusout will trigger on the parent element when you focus on one of the child elements. A solution I can think of would be to keep track of the current row using a variable. The pseudo code might work something like this:

var row = '';
$(table_element).click(function() { 
                           focused_row = $(this).parent();
                           if(row != '' && focused_row != row) {
                               //code to save edits, user clicked different row
                           }
                           row = focused_row;
                       });
like image 29
Brian Glaz Avatar answered Oct 13 '22 09:10

Brian Glaz