Home > Blockchain >  How to show related options based on text field using jquery
How to show related options based on text field using jquery

Time:11-30

i am trying to achieve live seacrh. when i enter any text in the text field it should match with the text in available in options. then it should show the matching options under textbox. So far i have tried this. What i have achieved is i have got the matching text, and i am alerting it. But i want it to drop down list with matching results.

Code

<select name="location_to" class="full-width">
    <?php
        foreach ( $flight_locations as $flight_location ) {
            echo '<option value="' . esc_attr( $flight_location->term_id ) . '" ' . ' >' . esc_html( $flight_location->name ) . '</option>';
        }
    ?>
</select>


**jquery code**
$('#location_from_input').keyup(function(){
    
    var txt = $(this).val().toLowerCase();
    // window.alert(txt);
    // lenght  = this.value.length;

    $('#location_from>option').each(function () {
        var text  = $(this).text();
            textL = text.toLowerCase();
            // window.alert(txt);
            (textL.indexOf(txt) == 0) ? window.alert(text) : $(this).hide();
    });
})

I need your help. Thanks I Advance.

CodePudding user response:

You should disable the elements that don't match your search. Use $('selector').prop('disabled', true) to disable a given element.

References:

How to show disable HTML select option in by default?

CodePudding user response:

Here I tried to make a similar way based on your requirements, you can have a try

$('#selectText').keyup(function () {
        var txt = $(this).val().toLowerCase();
        // window.alert(txt);
        // lenght  = this.value.length;
        var hasMatch = false;
        var matchText = '';
        $('#select>option').each(function () {
            var text = $(this).text();
            textL = text.toLowerCase();
            // window.alert(txt);
            if (textL.indexOf(txt) == -1) {
                $(this).hide();
            } else {
                hasMatch = true;
                matchText = textL;

            }
        });
        if (hasMatch == true) {
            $('#select').val(matchText).change();
        } else {
            $('#select').val('No Match').change();
        }

    })

This will return "No Match" when there is no record for matching, also when there are multiple values can be selected, will display one of them as selected.

  • Related