JQuery detect dropdown value is selected even if it's not changed

前端 未结 7 1761
感动是毒
感动是毒 2021-01-05 01:29

Using JQuery or JavaScript, I want to detect when a user selects a value, even if they don\'t change the already selected value.

How can this be accomplished?

<
相关标签:
7条回答
  • 2021-01-05 02:25

    I've made a working jsfiddle only tested on firefox. I've managed to do what you want by adding a dummy option to the selectbox. This dummy option has a display:none style and won't be visible in the option list.

    DEMO

    <select id="myselect">
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3" selected="selected">three</option>
        <option value="4">four</option>
        <option class="dummy" style="display:none">dummy</option>
    </select>
    
    
    
    $('#myselect').on('focus',function(){    
        $(this).find("option.dummy").prop("selected", true);
    });
    
    $('#myselect').on('change',function(){
        var select=$(this);
        var text=select.find("option:selected").text();
    
        $('.dummy').attr('value',select.val()).text(text);
        alert(select.val());
    
    
    });
    
    0 讨论(0)
提交回复
热议问题