Select by search text in jQuery

I currently have code for filtering selection text, as shown below.

image image

When I enter text in the search field, it filters. But I need to select an option when it runs in a text field without filtering, as shown below.

image

<script src="./jquery.min.js"></script>
<script>
    jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
        return this.each(function() {
            var select = this;
            var options = [];
            $(select).find('option').each(function() {
                options.push({value: $(this).val(), text: $(this).text()});
            });
            $(select).data('options', options);
            $(textbox).bind('change keyup', function() {
                var options = $(select).empty().data('options');
                var search = $.trim($(this).val());
                var regex = new RegExp(search,"gi");

                $.each(options, function(i) {
                    var option = options[i];
                    if(option.text.match(regex) !== null) {
                        $(select).append(
                           $('<option>').text(option.text).val(option.value)
                        );
                    }
                });
                if (selectSingleMatch === true && $(select).children().length === 1) {
                    $(select).children().get(0).selected = true;
                }
            });            
        });
    };

    $(function() {
        $('#select').filterByText($('#textbox'), true);
    });  
</script>

In body tag 

<select id="select" size=10>
<option value="12">12</option>
<option value="1234567890">1234567890</option>
<option value="ARADHYA">ARADHYA</option>
<option value="HI">HI</option>
<option value="APPLE">APPLE</option>
</select>
<input id="textbox" type="text">

FIDDLE DEMO

+4
source share
2 answers

Your code will change a lot.

First, the selection must have an attribute multiple. In javascript you only need to set the property selectedfor the parameters that match. I created a violin to show its work, but it basically boils down to the following:

...
if (search == '') {
   $options.prop('selected', false);
   return;
}
$options.each(function() {
    var $option = $(this);
    $option.prop('selected', $.trim($option.text()).match(regex) !== null);
});
...

if , . , ( ). jQuery each .

.

+5

( ):

$('#textbox').keyup(function () {
    if ($('#textbox').val() != '') {
        $('option').each(function () {
            if ($(this).text().toLowerCase().match(new RegExp($('#textbox').val().toLowerCase())) != null) {
                $(this).attr("selected", "selected");
            } else {
                $(this).removeAttr("selected");
            }
        });
    } else {
        $('option').each(function () {
            $(this).removeAttr("selected");
        });
    }
});

JSFiddle

+1

Source: https://habr.com/ru/post/1599227/


All Articles