k_schultz k_schultz - 2 months ago 6
jQuery Question

Trying to select a single item from a <li> and place that value into a textbox

I have

<input type="text" id = "addressbox" size="30" onkeyup="showResult(this.value)">

<ul class="livesearch" id="livesearch" style="border: 1px solid rgb(165, 172, 178);">
<li><a href="#">ADDRESS1</a></li><br>
<li><a href="#">ADDRESS 2</a></li><br>
</ul>


and for javascript

$('.livesearch').click(function() {
var value = $(this).text();
var TheTextBox = document.getElementById("addressbox");
TheTextBox.value = value;
});


When I click on the link it selects all the addresses within the
<ul>
and not the single one I click, example, I click address 1 but in the textbox address1 and address2 show up....what am I doing wrong?

Answer

Why do you even mix pure JavaScript and jQuery? Stick with just one. My strong feeling is that the browser is following the link. Use either return false or event.preventDefault() to stop the browser from following the link.

Also, please do not use <br /> unnecessarily. Since you are making a dynamic update of elements, use event delegation like this:

$('.livesearch').on("click", "a", function(e) {
  e.preventDefault();
  $("#addressbox").val($(this).text());
});
* {margin: 0; padding: 0; list-style: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id = "addressbox" size="30" onkeyup="showResult(this.value)">

<ul class="livesearch" id="livesearch" style="border: 1px solid rgb(165, 172, 178);">
  <li><a href="#">ADDRESS1</a></li>
  <li><a href="#">ADDRESS 2</a></li>
</ul>

Comments