Click already selected option in select box

↘锁芯ラ 提交于 2019-12-12 03:39:12

问题


This seems like it should be easy, but the limitations of the <select> object are rather irritating. I have a select box with four options, and when you navigate to a page, the option is set to the page you are on. I want to make it so that the user can refresh the page by selecting the same option - that is, selecting the option that's already selected.

Unfortunately, the onclick event doesn't work across browsers. Most people recommend using onchange, but that doesn't work in the case I'm talking about. The approach I've been taking is to add an extra item at the top that holds what's currently selected and does nothing when clicked on, and then switch to that option after firing the onchange event, so that when the user re-selects the option they're actually changing. That's awkward though, because in the drop-down there are two of the same item, and I shouldn't have to do it.

What is a good cross-browser way to solve this problem? Something not terribly complicated and something in regular JavaScript would be preferable.


回答1:


This might help:

function onFocus(element){
    element.setAttribute('old-value',element.value);
    element.value='';
    console.log('reset');
}

function onBlur(element){
    if(element.value=='')
        element.value = element.getAttribute('old-value');
    element.removeAttribute('old-value');   
}

function onChange(element){
    console.log('New Value : '+ element.value);
}
<select id="mySelect"  onfocus="onFocus(this)" onchange="onChange(this)" onblur="onBlur(this);">
    <option value="" style="display:none;"></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
</select>



回答2:


Here you go with the solution

$("select[id=mySelect] option").click(function(){
    alert("HI");
});

This will alert -HI- everytime a click is made on an option. The change has also been made in the select box and event is also been performed.



来源:https://stackoverflow.com/questions/13767190/click-already-selected-option-in-select-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!