简体   繁体   English

如何通过复选框将html标记添加到textarea中?

[英]How to add html markup into a textarea via checkbox?

HTML 的HTML

<div class="thumbnail">
  <input type="checkbox" name="thing_5" value="valuable" id="thing_5">
  <label for="thing_5">
    <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/a/ac/U.S._Marines_in_Operation_Allen_Brook_(Vietnam_War)_001.jpg">
  </label>
</div>
<div class="thumbnail">
  <input type="checkbox" name="thing_5" value="valuable" id="thing_6">
  <label for="thing_6">
    <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/a/ac/U.S._Marines_in_Operation_Allen_Brook_(Vietnam_War)_001.jpg">
  </label>
</div>
<textarea id='txtarea'></textarea>

JQuery jQuery查询

$(document).ready(function() {
  $('.thumbnail :checkbox').change(function() {
    var urls = [];
    $(":checkbox:checked").each(function () {
      urls.push($(this).next("label").find("img").attr("src"));
    });
    if (urls.length)
      $("#txtarea").val("<li>" + urls.join("</li><li>") + "</li>");
    else
        $("#txtarea").val("");
  });
});

I need to be able to add <li> before the value and also be able to add/remove on checkbox checked/unchecked 我需要能够在值之前添加<li> ,还能够在选中/未选中的复选框上添加/删除

Only a small change will make it work in this. 仅需很小的更改即可使其工作。 You should check for the length of the url before doing anything on the textarea value: 在对textarea值进行任何操作之前,您应检查url的长度:

if (urls.length)
  $("#txtarea").val("<li>" + urls.join("</li><li>") + "</li>");
else
  $("#txtarea").val("");

Fiddle: http://jsfiddle.net/u9myz270/ 小提琴: http : //jsfiddle.net/u9myz270/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM