Home > Software design >  How to add text to the input box by clicking on the event?
How to add text to the input box by clicking on the event?

Time:10-06

Specifically, I want to add popular keywords to the search, where users can add text to the search box by clicking on the keywords. Here is an example.

$(document).ready(function() {
  $('#searchHot li').click(function() {
    var name = $('#searchHot li').val();
    $('#searchInput input').text(name);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div id="searchInput">
    <input type="search">
  </div>
  <ul id="searchHot">
    <span>Popular:</span>
    <li>AAA</li>
    <li>BBB</li>
    <li>CCC</li>
    <li>DDD</li>
  </ul>
</div>

It's not working as expected, sorry I'm a jquery newbie and I'm not sure what it's getting wrong.

Any help, thanks in advance!

CodePudding user response:

There's a few issues with the current implementation:

  1. The click handler is trying to get the text of #searchHot li, but you want the text of the clicked list item, not all of them. You could get a reference to the clicked item with $(e.target), with e being the event passed to the click function handler.
  2. When getting the text of the list item, you are using .val() but it's not an input and you likely just want the text content, which can be done with .text().
  3. When setting the value of the input, you are using .text(name) but you want to set the input value to be the content, which can be done with .val(name).

The follow code snippet should show a version where clicking on the list item will replace the contents of the input field.

$(document).ready(function() {
  $('#searchHot li').click(function(e) {
    var name = $(e.target).text();
    $('#searchInput input').val(name);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div id="searchInput">
    <input type="search">
  </div>
  <ul id="searchHot">
    <span>Popular:</span>
    <li>AAA</li>
    <li>BBB</li>
    <li>CCC</li>
    <li>DDD</li>
  </ul>
</div>

If you don't want the input to be replaced and instead appended to, that could be done with something like this instead:

var input = $('#searchInput input');
input.val(input.val()   ' '   name);
  • Related