Home > Software design >  Is there any way to work this keyword search functionality if we assign value directly without typin
Is there any way to work this keyword search functionality if we assign value directly without typin

Time:01-13

I have implemented a search functionality and it's working if we search the keyword by typing.

<input type="text"  id="searchTheKey" placeholder="Enter the keywords to search.....">
</label>
<ul id="matchKey">
<li id="subjectName">JavaScript</li>
<li id="teacherName"><a href="#">John Smith</a></li>
<li id="subjectName">Java</li>
<li id="teacherName"><a href="#">David Miller</a</li>
<li id="subjectName">MongoDB</li>
<li id="teacherName"><a href="#">Carol Taylor</a></li>
</ul>
<script>
   $("#searchTheKey").on('keyup', function(){
      var value = $(this).val().toLowerCase();
      $("#matchKey li").each(function () {
         if ($(this).text().toLowerCase().search(value) > -1) {
            $(this).show();
            $(this).prev('.subjectName').last().show();
         } else {
            $(this).hide();
         }
      });
   })
</script>

But in the case of assigning value in the input box directly, the search functionality is not working.

example : $(".txtInput").val("MongoDB"); is there any way to solve this issue, that this should work in both case.

CodePudding user response:

You can add .trigger("keyup") to your $(".txtInput").val("MongoDB")

Demo

$("#searchTheKey").on('keyup', function() {
  var value = $(this).val().toLowerCase();
  $("#matchKey li").each(function() {
    if ($(this).text().toLowerCase().search(value) > -1) {
      $(this).show();
      $(this).prev('.subjectName').last().show();
    } else {
      $(this).hide();
    }
  });
})

$(".mongo").click(function() {
  $(".txtInput").val("MongoDB").trigger("keyup")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text"  id="searchTheKey" placeholder="Enter the keywords to search.....">

<ul id="matchKey">
  <li id="subjectName">JavaScript</li>
  <li id="teacherName"><a href="#">John Smith</a></li>
  <li id="subjectName">Java</li>
  <li id="teacherName"><a href="#">David Miller</a></li>
  <li id="subjectName">MongoDB</li>
  <li id="teacherName"><a href="#">Carol Taylor</a></li>
</ul>


<button >search for mongo</button>

CodePudding user response:

Relevant snippet: $("#searchTheKey").on('keyup', function(){

You bind your function on keyup, this way it won't execute since changing input value programmatically does not trigger a keyup event.

Easiest way would be to use .trigger('keyup') when you change the input value, like suggested by Carsten.

  •  Tags:  
  • Related