简体   繁体   中英

How to create case-insensitive text search

I have a search function that works perfectly for my application except that I can't figure out how to make it case-insensitive. Here is an example of some HTML:

 <div id='search_count'>
   <div id='count'><?php  get_count('notes', 'tasks') ?>
   </div>
    <input type="text" id='search_notes' placeholder='Search'/>
   </div>

   <div class='task'>
    301 closet  
   </div>

 <div class='notes'>
 <p>The old manager opened a panel that needs to be closed.</p>
 </div>

 <div class='task'>vacuum halls </div>

 <div class='notes'><p>The halls need to be vacuumed every week!</p></div>

This JavaScript will filter the divs with class='notes' just like I want, but only case-sensitive. How can I do this case-insensitive?

$("#search_notes").keyup(function () {
    var search_notes = $(this).val();
    $('.task, .notes').css('display', 'none');

    $("div.notes:contains(" + search_notes + ")")
        .css('display', 'block')
        .prev().css('display', 'block');


    var count = $('div.notes').filter(function () {
        return $(this).css('display') !== 'none';
    }).length;

    $('#count').text(count);
});

You have to test both lowercased values against each other using toLowerCase() method:

var search_notes = $(this).val().toLowerCase();

$('.task, .notes').css('display', 'none');

$('div.notes').filter(function() {
  return $(this).text().toLowerCase() === search_notes;
}).forEach(function() {
  $(this)
    .css('display', 'block')
    .prev()
    .css('display', 'block');
});


var count = $('div.notes').filter(function() {
return $(this).css('display') !== 'none';
}).length;

$('#count').text(count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM