开发者

JQuery. Why can't I insert an html img tag in a textarea?

开发者 https://www.devze.com 2023-01-04 00:28 出处:网络
TextArea looks like: <textarea id=\"MessageContent\" name=\"MessageContent\"></textarea> JQuery looks like:

TextArea looks like:

<textarea id="MessageContent" name="MessageContent"></textarea>

JQuery looks like:

 $("#insert").live("click", function () {
             var t = "<img width='" + result.width + "' height='" + result.height + "' alt='" + result.descr + "' src='/Images/" + result.message + "' />";
             $("#MessageContent").html($("#MessageContent").html() + t);
             $("#MessageContent").focus();

             $("#backgroundPopup").fadeOut("fast");
             $("#popupContact").fadeOut("fast");
         });      //live

I can insert simple text, but开发者_StackOverflow社区 can't insert any HTML tag.


You want to use .val() here instead of .html() to set a <textarea>'s value (otherwise the value isn't encoded, or used properly), like this:

$("#insert").live("click", function () {
  var t = "<img width='" + result.width + "' height='" + result.height + "' alt='" + result.descr + "' src='/Images/" + result.message + "' />";
  $("#MessageContent").val($("#MessageContent").val() + t);
  $("#MessageContent").focus();

  $("#backgroundPopup").fadeOut("fast");
  $("#popupContact").fadeOut("fast");
});

You can also shorten it a bit by passing a function to .val(), like this:

$("#insert").live("click", function () {
  $("#MessageContent").val(function(i, val) {
     return val + "<img width='" + result.width + "' height='" + result.height + "' alt='" + result.descr + "' src='/Images/" + result.message + "' />";
   }).focus(); 
  $("#backgroundPopup").fadeOut("fast");
  $("#popupContact").fadeOut("fast");
});
0

精彩评论

暂无评论...
验证码 换一张
取 消