user1355300
user1355300

Reputation: 4987

append an element ID in a textarea with jQuery

On clicking a li item, i want to insert its ID in the text area. I have following code, it works fine only if I do not enter anything in the textarea. If I enter anything in textarea (even if I remove it), it wont work. How I can fix that?

Check the demo to see the problem.

$("ul li").click(function(event) {
    var eid = $(this).attr('id');
    $(".text").append(eid);
});

JSFiddle: http://jsfiddle.net/2nt7vkwe/

Upvotes: 0

Views: 529

Answers (4)

Alex Char
Alex Char

Reputation: 33218

You don't need to use append. You can use val():

$("ul li").click(function(event) {
  var eid = $(this).attr('id');
  $(".text").val($(".text").val() + " " + eid);
});
textarea {
  height: 100px;
  width: 300px;
  margin-bottom: 20px;
}
ul li {
  float: left;
  margin-right: 5px;
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
}
ul li img {
  max-width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="text">

</textarea>

<div class="list">
  <ul>
    <li id="what">
      <img src="https://cdn2.iconfinder.com/data/icons/very-emotional-emoji/64/72_EmoticonsHDcom.png" />
    </li>
    <li id="wasntme">
      <img src="https://cdn2.iconfinder.com/data/icons/very-emotional-emoji/64/40_EmoticonsHDcom.png" />
    </li>
    <li id="rockstar">
      <img src="https://cdn2.iconfinder.com/data/icons/very-emotional-emoji/64/26_EmoticonsHDcom.png" />
    </li>

    <li id="angry">
      <img src="https://cdn2.iconfinder.com/data/icons/very-emotional-emoji/64/70_EmoticonsHDcom.png" />
    </li>

  </ul>
</div>

Upvotes: 3

Arber Braja
Arber Braja

Reputation: 445

This should do the work:

http://jsfiddle.net/2nt7vkwe/7/

$("ul li").click(function(event) {
    event.preventDefault();
    var eid = $(this).attr('id');
     $(".text").val(eid);
    // $(".text").append(eid);
});

Upvotes: 0

scunliffe
scunliffe

Reputation: 63588

If your element with the class "text" is a textarea element try:

$("ul li").click(function(event) {
    var eid = $(this).attr('id');
    var oldVal = $(".text").val();
    $(".text").val(oldVal + eid);
});

Note that if you have more than one textarea you'll need to adjust this code to deal with multiples.

Upvotes: 2

Hackerman
Hackerman

Reputation: 12305

Check this out:

$("ul li").click(function(event) {
  var eid = $(this).attr('id');
  var texto = $(".text").val();
  $(".text").val(texto + eid);
});

Working fiddle: http://jsfiddle.net/robertrozas/2nt7vkwe/6/

Upvotes: 2

Related Questions