Putting cursor into dynamically added input fields with jQuery

Posted by Sandoichi on Stack Overflow See other posts from Stack Overflow or by Sandoichi
Published on 2011-11-19T01:22:15Z Indexed on 2011/11/19 1:50 UTC
Read the original article Hit count: 94

Filed under:
|

I wrote a script that allows users to click onto a table cell and edit the value with jQuery. Basically, when they click the cell, the HTML in the cell gets replaced with an input box and any text that was previously in the cell gets added to the input. My issue is that whenever they click on the cell, the input doesn't get focused and they have to click a second time to put the cursor in. I have tried a bunch of selectors with .focus() to try and put the cursor in but I'm not having any luck.

Here is the function that gets called when the user clicks on a cell:

function edit_cell()
        {   
            if($(this).hasClass('edit_box'))
                if(!$(this).hasClass('editable')){
                    $(this).addClass('editable');
                    string = $(this).text();
                    $(this).html("<input type='text' value='" + string + "'/>");
                }
        } 

Also, is there a way to make the size of the input box relative to the width of the cell it gets added too? I don't know how to relate the size attribute to the width for the cell...and it is driving me crazy!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about html