Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append() doesn't work after previously appended contents deleted

I convert user input urls to bbcode and append it to the textarea, but after you delete one of the lines I appended it won't append more(but you could see the newly appended values in the firebug,really strange).Here's my code:

$(function(){
    $(".addUrl").click(function(){
        $("#addUrl").slideDown();
    })
    $('#su').click(function(){
        if($("#u").val().length>3)
        addUrl($("#u").val());
        $("#u").val("");
    })
    $("input[value=\"x\"]").click(function(){$("#addUrl").fadeOut();})
})
function addUrl(e)
{
    patt="http[s]*:\/\/";
    if(e.match(patt))
        u=e;
    else
        u="http://"+e;
    $("textarea[name=\"content\"]").append("\n\r[url]"+u+"[/url]\n\r");
}

And here's the jsfiddle:http://jsfiddle.net/FpSsc/

like image 376
dotslashlu Avatar asked Dec 05 '11 08:12

dotslashlu


1 Answers

It's because you are changing the html inside the textarea which is the default value. It seems that as soon as you have set a new value (by typing or deleting something from the textbox) this default value is ignored.

To get round this you need to set the value of the textarea rather than append to the content:

function addUrl(e)
{
    patt="http[s]*:\/\/";
    if(e.match(patt))
        u=e;
    else
        u="http://"+e;

    var newVal = $("textarea[name=\"content\"]").val() + "\n\r[url]"+u+"[/url]\n\r"
    $("textarea[name=\"content\"]").val(newVal);
}

http://jsfiddle.net/infernalbadger/FpSsc/1/

Or as Felix recommended:

function addUrl(e)
{
    patt="http[s]*:\/\/";
    if(e.match(patt))
        u=e;
    else
        u="http://"+e;

    $("textarea[name=\"content\"]").val(function(i, v) { return v + "\n\r[url]"+u+"[/url]\n\r"; });
}
like image 114
Richard Dalton Avatar answered Sep 30 '22 00:09

Richard Dalton