Tod
Tod

Reputation: 187

Drop-down autocomplete

I want dropdown autocomplete matching letters to be bold, here is my code for dropdown autocomplete:

var states = {
  'Color': ['red', 'black', 'yellow', 'green', ],
  'Numbers': ['one', 'two', 'three', 'four']
};

function match(str) {
    str = str.toLowerCase();
    clearDialog();
    for (var i = 0; i < states.color.length; i++) {

        if (states.color[i].toLowerCase().includes(str)) {
            jQuery('.dialog').append('<div>' + states.color[i] + '</div>');
        }
    }
}

Upvotes: 0

Views: 917

Answers (2)

Davide Vitali
Davide Vitali

Reputation: 1035

First, you might want to perform a <span> tag insertion before appending the newly created div so that, creating a CSS class, you can set the bold font within, or even change its color or any other property later:

.dialog > div > .match {
    font-weight: 700;
}

Then, you can append this new text to your dialog

...append(‘<div>’ + text + ‘</div>’);

$(document).ready(function() {
    var states = {
        'Color': ['red', 'black', 'yellow', 'green', 'Dark Green', 'Light Grey'],
        'Numbers': ['one', 'two', 'three', 'four']
    };

    $('input').on('keyup', function () {
        match($(this).val());
    });

    function match(str) {
        str = str.toLowerCase();
        $('.dialog').empty();
        for (var i = 0; i < states.Color.length; i++) {
            if (states.Color[i].toLowerCase().includes(str)) {
                var mStart = states.Color[i].toLowerCase().indexOf(str);
                var mEnd = mStart + str.length;
                var text = states.Color[i].slice(0, mStart);
                text += '<span class="match">';
                text += states.Color[i].slice(mStart, mEnd);
                text += '</span>';
                text += states.Color[i].slice(mEnd);
                $('.dialog').append('<div>' + text + '</div>');
            }
        }
    }
});
.dialog > div > .match {
  font-weight: 700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" />
<div class="dialog">

Upvotes: 2

Asav Vora
Asav Vora

Reputation: 71

It can be possible by using <strong> tag on append function. To achieve this you need to split it into two parts of word 1).Non-matched part and 2). Matched part.

For matched part put string into <strong> tag and other simply append

for reference check this W3School Tryit Editor link of Autocomplete.

Helpful code:

b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);

where b = jQuery('.dialog').html()

Upvotes: 0

Related Questions