简体   繁体   中英

Case-insensitive autocomplete in Javascript

I have a javascript code that is used for autocomplete functionality. It highlights the text that is entered in a search box and matches it with the text in a database. This is case-sensitive, so it only highlights the text which is in the database table. I want the search to be case-insensitive. This is my existing code:

 <script type="text/javascript">
$(function() {
    var availableTags = [<?php echo $tagsString; ?>];

    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
 $.extend( $.ui.autocomplete.prototype, {
    _renderItem: function( ul, item ) {
        var term = this.element.val(),
            html = item.label.replace( term, "<span class='f1'>$&</span>" );
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( $("<a></a>").html(html) )
            .appendTo( ul );
    }
});

</script>

in your database code use LOWER on both sides of the equasion.

... WHERE LOWER(db_field) = LOWER(:text) ...

Or you can cast the input to lower before giving it to the database and omit the right LOWER in this case

In case of LIKE

... WHERE LOWER(db_field) like '%' || LOWER(:text) || '%' ...

Please always quote properly or better use perpared statements to prevent SQL injections.

EDIT: Found a cleaner way using only bindings without quoting

I assume you are using MySQL.

You can lower field name and searched value,

WHERE LOWER( db_table.db_field ) = LOWER(:text) // find exact match

or use like with lower:

WHERE  LOWER( db_table.db_field ) LIKE '%' || LOWER(:text) || '%'  // find all that have this text as substring

But in boh cases remember to use parametrized statemenets, in order to avoid SQL injection atacks.

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