js list search code example

Example 1: function search in javascript array

// function to search array using for loop
function findInArray(ar, val) {
    for (var i = 0,len = ar.length; i < len; i++) {
        if ( ar[i] === val ) { // strict equality test
            return i;
        }
    }
    return -1;
}

// example array
var ar = ['Rudi', 'Morie', 'Halo', 'Miki', 'Mittens', 'Pumpkin'];
// test the function 
alert( findInArray(ar, 'Rudi') ); // 0 (found at first element)
alert( findInArray(ar, 'Coco') ); // -1 (not found)

Example 2: js filter text

<script>
    $('input[name="search_field"]').on("keyup", function() {
        filtrate($(this).val().toLowerCase());
    });

    function filtrate(searched) {
        $(".filter-key > h3").filter(function() {
            var isHidden = ($(this).text().toLowerCase().indexOf(searched) > -1) ? 'block' : 'none';
            $('.filter-key').css('display', isHidden);
        });
    }
</script>

Tags:

Html Example