How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

后端 未结 8 1513
天命终不由人
天命终不由人 2020-11-28 23:29

I have the following markup:


                        
    
提交评论

  • 2020-11-29 00:06

    JavaScript code:

    • on mousedown event: set selectedIndex property value to -1
    • on change event: handle event

    The only drawback is that when the user clicks on the dropdown list, the currently selected item does not appear selected

    0 讨论(0)
  • 2020-11-29 00:10

    You have to add empty option to solve it,

    I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.

    <select onChange="jsFunction()" id="selectOpt">
        <option value="1" onclick="jsFunction()">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    
    function jsFunction(){
      var myselect = document.getElementById("selectOpt");
      alert(myselect.options[myselect.selectedIndex].value);
    }
    
    0 讨论(0)
  • 2020-11-29 00:15

    Try this. Just add an empty option. This will solve your problem.

    <select onchange="jsFunction()">
        <option></option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>​
    
    0 讨论(0)
  • 2020-11-29 00:18

    For this problem, I have finally put a new <i> tag to refresh the select instead. Don't try to trigger an event if the selected option is the same that the one already selected.

    If user click on the "refresh" button, I trigger the onchange event of my select with :

    const refreshEquipeEl = document.getElementById("refreshEquipe1");
    
    function onClickRefreshEquipe(event){
        let event2 = new Event('change');
        equipesSelectEl.dispatchEvent(event2);
    }
    refreshEquipeEl.onclick = onClickRefreshEquipe;
    

    This way, I don't need to try select the same option in my select.

    0 讨论(0)
  • 2020-11-29 00:21

    Just set the selectIndex of the associated <select> tag to -1 as the last step of your processing event.

    mySelect = document.getElementById("idlist");
    mySelect.selectedIndex = -1; 
    

    It works every time, removing the highlight and allowing you to select the same (or different) element again .

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