开发者

Javascript search for substring

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?

Here is my code so far, I have it working so that the showMe method will only display the divs selected, I just need the substring code to work now. Could someone please help?

   <html>

<head>
<script type="text/javascript"> 
<!-- 
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;
} 
//--> 
</script>
</head>

<body>

<form>
<label for="search">Search:</label>
            <input type="text" name="search" id="search" onkeyup="dynamicSearch()"/>

<input type="checkbox" name="modtype" value="value1" onclick="showMe('div1', this)" />value1

<input type="checkbox" name开发者_StackOverflow="modtype" value="value2" onclick="showMe('div2', this)" />value2

<input type="checkbox" name="modtype" value="value3" onclick="showMe('div3', this)" />value3

<input type="checkbox" name="modtype" value="value4" onclick="showMe('div4', this)" />value4

<input type="checkbox" name="modtype" value="value5" onclick="showMe('div5', this)" />value5

<div class="row" id="div1" style="display:none">Show Div 1</div>
<div class="row" id="div2" style="display:none">Show Div 2</div>
<div class="row" id="div3" style="display:none">Show Div 3</div>
<div class="row" id="div4" style="display:none">Show Div 4</div>
<div class="row" id="div5" style="display:none">Show Div 5</div>
</form>

</body>

</html>


This sort of stuff is a lot easier with jQuery.

For example, your dynamicSearch function could be replaced with this:

function dynamicSearch() {
    var val = $('#search').val();
    if (val == '') val = '-1';
    var srch = new RegExp(val, "gi");

    $('.row').each(function(i, el) {
        if ($(this).text().match(srch)) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}

and you can get animation effects for free too, which you can't easily do just be setting the CSS display property.

I've put a working fiddle up at http://jsfiddle.net/alnitak/nLxc4/ which I think does what you're asking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜