简体   繁体   中英

How to add html markup into a textarea via checkbox?

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

$(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

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:

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

Fiddle: http://jsfiddle.net/u9myz270/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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