Prasanth Klr Prasanth Klr - 1 year ago 65
HTML Question

how to match the single string and return whole string using js

I have code :
To search a single string and return whole string.

$(document).ready(function() {
$('button').click(function (){
var search = $('#input').val();
var str = $('#file').html();
var output=str.match(search );
document.getElementById("result").innerHTML = output;

if (search.value.length > 0) {
$(".oh").show().filter(function () {
return $('#input').find('li').text().toLowerCase().indexOf($("search").val().toLowerCase()) == -1;
else {
document.getElementById( 'oh' ).style.display = 'block';

<script src=""></script>
<script src="searchbox.js"></script>

<input type="text" id="input">

<p id="result"></p>
<div id="file"class="oh"style="display:none;">
<li>happy sunday</li><li>good morning</li><li>good evening</li><li>oh my god</li>I like u</li><li>wonderful day</li>

<li>good aftnoon</li>



For example:

`input = good
output = good morning,
good night,
good noon`

`input = morning,
output = good morning`

Its like a search box inside html
Please help me with any suggestion or correct my code its more helpful for me i have use jquery and index() are using but its not work

Jai Jai
Answer Source

Check this, i have updated your markup little bit and changed the code to work:

$(document).ready(function() {
  $('button').click(function() {
    var search = $('#input').val();  // get the search term
    var $lis = $('#file li'); // all the existing li items to filter/search
    var $resUl =  $('#result ul'); // the ul to show results

    var o = $ { // map will let you loop through list items
      if (this.textContent.indexOf(search) != -1) { // check if the current li in the iteration has the search term
        return $(this).clone(); // if yes then return a copy of it.
    }).get(); // .get() will create an array when used with .map()
    $resUl.empty(); // always clear the result ul 
    $.each(o, function(i, item) { // loop through the array created via filter
      $resUl.append(item).find('li').fadeIn(); // here append them as lis are hidden so fade them in the view to show.

#file li {
  display: none;
<script src=""></script>

<input type="text" id="input">

<div id="result">
<ul id="file">
  <li>happy sunday</li>
  <li>good morning</li>
  <li>good evening</li>
  <li>oh my god</li>
  <li>I like u</li>
  <li>wonderful day</li>
  <li>good aftnoon</li>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download