简体   繁体   中英

How to trigger a callback function when select list text changes (before onchange event fires)?

I have a <select> field like the below:

<select id="my-list" class="default">
    <option value=0 selected disabled>Select an item</option>
    <option value=1>First Item</option>
    <option value=2>Second Item</option>
    <option value=3>Third Item</option>
</select>

The default class on the <select> element sets the color to red (indicating to the user that an option needs to be selected here).

Once the user selects an item the class is removed so the color changes to black.

Now what I'm trying to achieve is that the color changes as soon as the text in the select box changes. The onchange event only fires if the user clicks on an item in the list or presses ENTER or the element loses focus.

But if the user hits S for example the text will change to "Second item" and the color remains red until he presses ENTER or tabs out of the field.

Listening for keydown events doesn't work because if the user hits say X the event fires but the text won't change because there is no matching item.

One possible solution could be to use the keydown event and then compare the text to "Select an item" though it doesn't seem very elegant. And how would I get the text that is displayed? jQuery's .text() or .html() return all the options, not just what is displayed.

After writing the last paragraph of my question the answer came to me.

Typing into a select box or using the up and down arrow keys will set the selected attribute to the option displayed. Using the keyup event instead of the keydown event can then be used to simply check the value of the selected option and if it's not 0 the class is removed and the color changes.

$("#my-list").keyup(function(){
    if ($("#my-list option:selected").val() !== 0){
        $("#my-list").removeClass("default");
    }
});

It seems a bit clumsy so perhaps there is a better way, but it works.

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