Detecting interaction with select box

前端 未结 3 2035
庸人自扰
庸人自扰 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:19

    I think focus() function will help you..try this: http://api.jquery.com/focus/

    0 讨论(0)
  • 2020-12-21 12:20

    I have no idea if it would work just from the top of my head if you could attach an event handler to the select box option element and on click store its value.

    works with mouse, doesn't work with keyboard http://jsfiddle.net/w4DEJ/4/

    0 讨论(0)
  • 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.

    <select>
        <option style="display: none"></option>
        <option>First</option>
        <option>Second</option>
        <option>Third</option>
    </select>​
    

    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/

    0 讨论(0)
提交回复
热议问题