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 here is a second function that adds a new <tbody> and a new table row, with the first cell containing an active input field.
function add_ex(){
string = "<tbody><tr><td><input type='text'></td></tr></tbody>";
$(this).parents('tbody').before(string);
}
This works – just get an explicit reference to the new input element and
.focus()on it:Note that this also avoids the potentially error prone string concatenation when you create the
<input>element.Working example at http://jsfiddle.net/alnitak/SpkZG/
For your second snippet, create the elements straight away, put them into the DOM, then focus on the single element you need: