HandsomeRob
HandsomeRob

Reputation: 445

Dynamically added textarea doesn't work

Have a table I'd like to make editable line by line, user clicks on a cell containing text and it changes to text area.

Textarea adds fine, but is totally non-functional.

Here's a fiddle

Or code of what I'm trying to do?

<div id="click"></div>

#click {
    width: 200px;
    height: 100px;
    border: 1px solid black;
}

$(function(){
    $('#click').click(function(){
        $(this).html("<textarea></textarea>");
    });
});

Upvotes: 2

Views: 103

Answers (2)

krishwader
krishwader

Reputation: 11381

add a focus event after you add the textarea.

$(function () {
    $('#click').click(function () {
       $(this).html("<textarea></textarea>").find("textarea").focus();
    });
});

Updated fiddle : http://jsfiddle.net/na7sZ/2/

You could also do it this way :

$('#click').click(function () {
        var textarea = $('<textarea/>');
        $(this).html(textarea);
        textarea.focus();
});

Fiddle : http://jsfiddle.net/na7sZ/5/

Upvotes: 2

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

That is because your textarea is inside the click div, so a click on the textarea is also a click on the div, wich remove/create a new textarea.

Add this to you code :

$('#click').on('click', 'textarea', function(e){
    e.stopPropagation()
})

It will stop the event from bubbling and not recreate a textarea.

Fiddle : http://jsfiddle.net/na7sZ/4/

Upvotes: 1

Related Questions