Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass <li>text without replace the text on textbox

I got school homework for today. I can pass the emoji to a textbox already but it will replace the previous emoji or text on the textbox if clicked. I want to know how to not replace the textbox text if I clicked and able to keep input emoji or text. Sorry for my bad english if you guys don't understand.

$(document).ready(function () {
    $("ul").hide();
    $("input.btnemoji").click(function () {
        $("ul").toggle();
        $("ul.emoji li").click(function () {
            $("#ToSend").val($(this).text());
        });
    });
});
<asp:Textbox id="ToSend" runat="server" Width="300px"></asp:Textbox>
<input type="button" class="btnemoji" value="&#x1F600;" />
<ul class="emoji">
    <li>😀</li>
    <li>😂</li>
    <li>😎</li>
    <li>😍</li>
    <li>😁</li>
</ul>
like image 729
Zun Ping Avatar asked Feb 05 '23 11:02

Zun Ping


1 Answers

To add to the existing value you need to append to the val() in the input instead of replacing it each time. To do this you can pass a function to the val() method which handles the appending for you, like this:

$(document).ready(function() {
  $("ul").hide();

  $("input.btnemoji").click(function() {
    $("ul").toggle();
  });

  $("ul.emoji li").click(function() {
    var $li = $(this);
    $("#ToSend").val(function(i, v) {
      return v + $li.text();
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ToSend" width="300px">
<input type="button" class="btnemoji" value="&#x1F600;" />
<ul class="emoji">
  <li>😀</li>
  <li>😂</li>
  <li>😎</li>
  <li>😍</li>
  <li>😁</li>
</ul>

Also note that I moved the $("ul.emoji li").click() handler outside of the one for .btnemoji as you were repeatedly adding new event handlers each time the ul was toggled.

like image 117
Rory McCrossan Avatar answered Feb 08 '23 01:02

Rory McCrossan