Detecting interaction with select box

前端 未结 3 2040
庸人自扰
庸人自扰 2020-12-21 11:48

How (using javascript or jQuery) can I detect when a value has been selected from a select box, even if it\'s the same option as was previously selected (i.e. no change even

3条回答
  •  失恋的感觉
    2020-12-21 12:21

    The only solution I found workable is to cause change event by setting the value of select to some other on mousedown. In the markup I created one extra option (i.e. the first child) and made it hidden (hides perfectly in Chrome/FF/Safari, IE as usual). So it looks fine.

    Then using jQuery we bind change and mousedown events in a way that when mousedown triggers, select resets its value to the value of the hidden option.

    $("select").on({
        change: function() {
            console.log($(this).val());
        },
        mousedown: function() {
            $(this).val($(":first", this).val());
        }
    });​
    

    DEMO: http://jsfiddle.net/LzNrS/

    UPDATE: In order to preserve the selected value when user has clicked on select but decided not the choose anything, we can modify the code a bit adding blur event and updating mousedown.

    var special = ""; // special hidden option value
    var value = ""; // temporary variable
    
    $("select").on({
        change: function() {
            console.log($(this).val());
        },
        mousedown: function() {
            if (this.value == special) {
                $(this).val(value);
                return;
            }
            value = this.value;
            $(this).val(special);
        },
        blur: function() {
            if (this.value == special)
                $(this).val(value);
        }
    });​
    

    DEMO: http://jsfiddle.net/LzNrS/1/

提交回复
热议问题