Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any way to work this keyword search functionality if we assign value directly without typing

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

<input type="text" class="txtInput" 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" class="txtInput" 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 class="mongo">search for mongo</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading