Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery putting content of a paragraph in a textarea

I tried to do this for replacing a paragraph with a text area with the same content.

function edit() {
    var wdith = $("p").css('width')
    $("p:first").replaceWith("<textarea class='edit'>" + $("p:first").text() + "</textarea>")
    $(".edit").css("width", wdith)
}
$("#replace").click(edit);

Demo

But it doesn't work correctly. There are spaces before and after the text.
How do I fix it?

like image 550
kritya Avatar asked Aug 15 '11 09:08

kritya


1 Answers

You script is doing as it says on the tin. You're getting spaces because you have spaces and line breaks within your <p> tags.

To remove the text formatting, try this: http://jsfiddle.net/z9xCm/18/

function edit() {
    var wdith = $("p").css('width');
    var p = $("p:first");
    var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();
    p.replaceWith("<textarea class='edit'>" + t + "</textarea>")
    $(".edit").css("width", wdith)
}
$("#replace").click(edit);

First, we remove the line breaks, then removed multiple repeated spaces, then trim spaces at the beginning and end of the text.


Somewhat off topic, but that can also be rewritten as : http://jsfiddle.net/z9xCm/52/

$("#replace").click(function() {
    var p = $("p:first");
    p.replaceWith($("<textarea/>", {
        "class": "edit",
        "text": p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
        "css": { "width": p.css('width') }
    }));
});

Here's the same thing, but in a less compact and commented form.

$("#replace").click(function() { /* assign anonymous function to click event */

    var p = $("p:first"); /* store reference to <p> element */

    /* get p.text() without the formatting */
    var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();

    /* create new textarea element with additional attributes */
    var ta = $("<textarea/>", {
        "class": "edit",
        "text": t,
        "css": {
            "width": p.css('width')
        }
    });

    p.replaceWith(ta); /* replace p with ta */
});

Note that the $("...", {...}) syntax for creating new elements with attributes was only introduced in jquery 1.4.

like image 158
Shawn Chin Avatar answered Sep 25 '22 16:09

Shawn Chin