0

I'm trying to implement a jquery live input. When user starts typing in input, list of suggestions will appear below the input. From that list of options, user should be able to click one of them and text of that option should be in the input.

Here's the process so far https://jsfiddle.net/eckae003/1/

HTML

<input type="text" name="subject" id="my_input"/>
<ul>
<li><a href="#">English</a></li>
<li><a href="#">General English</a></li>
<li><a href="#">Business English</a></li>
<li><a href="#">French</a></li>
<li><a href="#">Russian</a></li>
<li><a href="#">German</a></li>
</ul>
<span id="label"></span>

jQuery

$("ul li a").click(function(){
    $("input#my_input").attr("value", $(this).text());
  $("span#label").html($(this).text());
})

$("input#my_input").keyup(function(){
    var text = $(this).val();
  $("ul li").each(function(){
    if ($(this).text().search(new RegExp(text, "i")) < 0) {
      $(this).fadeOut();
    } else {
      $(this).show();                
    }
  });
})

It's working on 1.8.3 version, but I wanted to do this in newer versions of jQuery.

Akmal
  • 7
  • 4
  • Do you have a specific issue with the code? Your fiddle link works fine in 1.10, and as you can see in the following fiddle the code works fine in jQuery 2.1.4: https://jsfiddle.net/eckae003/2/. – Rory McCrossan Jan 26 '16 at 10:28

1 Answers1

0

Use

$("input#my_input").val($(this).text());

instead of

$("input#my_input").attr("value", $(this).text());

Nice explanation from https://stackoverflow.com/a/8312886/2445864:

There is a big difference between an objects properties and an objects attributes

See this questions (and its answers) for some of the differences: .prop() vs .attr()

The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.

Updated Fiddle: https://jsfiddle.net/eckae003/4/

Community
  • 1
  • 1
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74