Search code examples
jqueryeventsjeditable

jeditable on a label, how do I keep it from losing focus on click?


I'm building a simple script that allows a user to add telephone numbers dynamically. These are inputs paired with a labels which can all be edited on the fly. I'm using jeditable for the labels but then I've come across a small problem, if a user tries to click inside the input box of the label the browser will detect a click on the label and place the focus on the input element of the label's "for" attribute.

I tried the following:

$(selector).find('input').live('focus', function(){
    $(selector).click(function(e){
        e.preventDefault;
        return false;
    });
}).live('blur', function(){
    //somehow reattach the behaviour here?
});

Essentially "selector" holds the selector for my jeditable label. I find the input inside of it and on focus I disabled the default behaviour of the label. This keeps the label from changing the focus. However, I do not know how to undo this. I supposed I could toggle a boolean flag and then call seperate method that would prevent the default but I have a feeling that there must be a much cleaner way to do this, any suggestions?


Solution

  • An alternative is to remove the for attribute when the label is being edited, and then add that attribute back after the editing.

    // store the "for" attr in the element's data
    $('label').each(function() {
        $(this).data('for', $(this).attr('for'));
    });
    
    $('label').editable('...', {
        ...
        onreset: function() {
            var $label = $(this).parent();
            $label.attr('for', $label.data('for'));
        }
    }).click(function() {
        $(this).removeAttr('for');
    });
    

    See it in action: http://jsfiddle.net/G8QuA/.