Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace and append with Javascript

I have a comment system in which I want to realize inline-editing (when someone knows a good plugin or something similar please don't hesitate to give me a name) and found a Javascript snippet which replaces the text with a textarea and the text as the value of that textarea.

But now I need to add a button (submit button) to that textarea so that the user could save the text he edited.

My code looks now like

<span id="name">comment</span>

<div onclick="replacetext();">test</div>

<script type="text/javascript">
    function replacetext(){
            $("#name").replaceWith($('<textarea>').attr({ id: 'name', value: $('#name').text() }));
    </script>

I've tested it out with $("#name").append('<button>yes</button>'); but it didn't work.

like image 657
John Brunner Avatar asked Dec 02 '12 15:12

John Brunner


2 Answers

The solution can be tried out using the following jsFiddle: http://jsfiddle.net/adb8X/5/

The line I believe you are after is:

  $('<button>yes</button>').insertAfter("#name");

The code above inserts a newly created DOM element (yes) right after the DOM element with the specified id in the target selector ("#name").

More about insertAfter here: http://api.jquery.com/insertAfter/

If you want to insert it into replacetext(), it will become:

function replacetext() {
    $("#name").replaceWith($('<textarea>').attr({
        id: 'name',
        value: $('#name').text()
    }));

    $('<button>yes</button>').insertAfter("#name");

} 

Note: I also corrected your jsFiddle. Please check here: http://jsfiddle.net/adb8X/5/ (There were problems with the settings and a small typo if I recall correctly). The corresponding line in that is:

 $("#name").append( $('<button>hi</button>') );
like image 172
Miltos Kokkonidis Avatar answered Sep 20 '22 13:09

Miltos Kokkonidis


function replacetext() {

    $("#name").replaceWith($('<textarea>').attr({
        id: 'name',
        value: $('#name').text()
    }));
   $('#name').after('<button id="test">test</button>');
}

$('#test').live("click",function(){
   alert("I am a newly-created element and .click won't work on me.");

});

You can't use .append() in a textarea because you can't "insert content" or append to it (there are other workarounds for that). You can do that in DIV, paragraph tag, or whatever that can act as a container.

http://api.jquery.com/append/
http://api.jquery.com/after/
http://api.jquery.com/live/ or .on() http://api.jquery.com/on/

like image 39
Wap Avatar answered Sep 23 '22 13:09

Wap