I recently work with this Fiddle http://jsfiddle.net/GeJkU/
    function divClicked() {
        var divHtml = $(this).html();
        var editableText = $("<textarea />");
        editableText.val(divHtml);
        $(this).replaceWith(editableText);
        editableText.focus();
        // setup the blur event for this new textarea
        editableText.blur(editableTextBlurred);
    }
    function editableTextBlurred() {
        var html = $(this).val();
        var viewableText = $("<div>");
        viewableText.html(html);
        $(this).replaceWith(viewableText);
        // setup the click event for this new div
        viewableText.click(divClicked);
    }
    $(document).ready(function () {
        $("div").click(divClicked);
    });
It will replace div tags with textarea when i click the div. My question is, how can i replace div tags with textarea when i click a button using above javascript?
Any Suggestions?
Assuming, I have understood your question, you can try the below.
HTML: Add a button like below after every div.
<div>If no background color is set on the Element, or its background color is set to 'transparent', the default end value will be white.</div>
<button class='btn'>Edit</button>
jQuery: Modify the code as below.
function divClicked() {
    var divHtml = $(this).prev('div').html(); //select's the contents of div immediately previous to the button
    var editableText = $("<textarea />");
    editableText.val(divHtml);
    $(this).prev('div').replaceWith(editableText); //replaces the required div with textarea
    editableText.focus();
    // setup the blur event for this new textarea
    editableText.blur(editableTextBlurred);
}
function editableTextBlurred() {
    var html = $(this).val();
    var viewableText = $("<div>");
    viewableText.html(html);
    $(this).replaceWith(viewableText);
    // setup the click event for this new div
    viewableText.click(divClicked);
}
$(document).ready(function () {
    $(".btn").click(divClicked); //calls the function on button click
});
Working Demo
I hope it helps you,
function divClicked(ele) {
    var divHtml = $(ele).parent().find('p').html();
    var editableText = $("<textarea />");
    editableText.val(divHtml);
    $(ele).parent().find('p').replaceWith(editableText);
    editableText.focus();
    // setup the blur event for this new textarea
    editableText.blur(function() {
        editableTextBlurred(this);
    });
}
function editableTextBlurred(ele) {
    $(ele).replaceWith($('<p>').html($(ele).val()));
}
$(document).ready(function() {
    $(".update").click(function() {
        divClicked(this);
    });
});
please check the demo version here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With