Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript search for substring
    text
    copied!<p>I am trying to write a javascript function that will search all of the specified divs in a html page for the substring contained in my search bar. How can I do this simply? </p> <p>Here is my code so far, I have it working so that the <code>showMe</code> method will only display the divs selected, I just need the substring code to work now. Could someone please help?</p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; &lt;!-- function dynamicSearch() { var val = document.getElementById('search').value; if (val == '') val = '-1'; var srch = new RegExp(val, "gi"); var els = document.getElementsByClassName('row'); for (var idx in els) { if (idx != parseInt(idx)) continue; var el = els[idx]; if (typeof(el.innerHTML) !== 'undefined') { console.log(el.innerHTML); if (srch.test(el.innerHTML)) { el.style.display = 'block'; } else { el.style.display = 'none'; } } } } function showMe (it, box) { var vis = (box.checked) ? "block" : "none"; document.getElementById(it).style.display = vis; } //--&gt; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;label for="search"&gt;Search:&lt;/label&gt; &lt;input type="text" name="search" id="search" onkeyup="dynamicSearch()"/&gt; &lt;input type="checkbox" name="modtype" value="value1" onclick="showMe('div1', this)" /&gt;value1 &lt;input type="checkbox" name="modtype" value="value2" onclick="showMe('div2', this)" /&gt;value2 &lt;input type="checkbox" name="modtype" value="value3" onclick="showMe('div3', this)" /&gt;value3 &lt;input type="checkbox" name="modtype" value="value4" onclick="showMe('div4', this)" /&gt;value4 &lt;input type="checkbox" name="modtype" value="value5" onclick="showMe('div5', this)" /&gt;value5 &lt;div class="row" id="div1" style="display:none"&gt;Show Div 1&lt;/div&gt; &lt;div class="row" id="div2" style="display:none"&gt;Show Div 2&lt;/div&gt; &lt;div class="row" id="div3" style="display:none"&gt;Show Div 3&lt;/div&gt; &lt;div class="row" id="div4" style="display:none"&gt;Show Div 4&lt;/div&gt; &lt;div class="row" id="div5" style="display:none"&gt;Show Div 5&lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload