Append () does not work after deleting previously added content

I convert the user urls to bbcode and add them to the text box, but after you delete one of the lines that I added, it will not be added anymore (but you could see the recently added values ​​in firebug, really strange). Here is 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 is the jsfiddle: http://jsfiddle.net/FpSsc/

+8
javascript jquery append
source share
2 answers

This is because you are changing the html inside the text field, which is the default value. It seems that as soon as you set a new value (by entering or deleting something from the text field), this default value is ignored.

To get around this, you need to set the value of the text field, and not add it 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"; }); } 
+6
source share

I can advise you to use val here

 function addUrl(e) { patt="http[s]*:\/\/"; if(e.match(patt)) u=e; else u="http://"+e; $("textarea[name=\"content\"]").val( $("textarea[name=\"content\"]").val() + "\n\r[url]"+u+"[/url]\n\r"); } 

try this addUrl function.

0
source share

All Articles