Execute function when selecting same option in select html tag

十年热恋 提交于 2020-01-03 05:52:39

问题


I execute functions throughout my cordova app, whenever someone clicks an <option> in the <select> dropdown box, by using the onChange="" HTML attribute. I would like to be able to execute the functions when they click the same option. onChange obviously won't work here. Is there some kind of work around to allow this to happen, so when the user clicks the same option that is already selected in the HTML select tag, it executes the method? This would enable me to delete some unsightly buttons that are only needed for when the user wants to choose the already selected option. Thanks.

Current code example of how I do things:

<select style="left:0; width:100%;" class="textColour" id="allLocationsDropDownTablet" onchange="if (typeof(this.selectedIndex) != undefined) {getClients();navigateToClientsList();this.blur();}"></select>

回答1:


Here is a much simpler solution than the one provided in the link:

Instead of adding classes, this solution works with a JS variable in which we 'cache' the last selected option and compare the currently selected option to it, then execute a function if it is the same. We also need a simple counter which will keep track of the amount of clicks (because the first click opens the dropdown).

To access <select> options you should use this.options[this.selectedIndex] & not just this.selectedIndex

So here we go for the setup: (Option 1 is always selected by default)

var $select = $('#allLocationsDropDownTablet'), 
    cache = 'Option 1', count = 0;

Now followed by the code: (inline comments for explanation)

$select.click(function(){
    var $this = $(this), sel;
    // just for testing purpose
    console.log(count);
    // if a click has preceeded the current click, execute comparison function
    if (count === 1) {
        // store the textvalue of the current option
        sel = this.options[this.selectedIndex].textContent 
            || this.options[this.selectedIndex].innerText; //IE8-
        // if current textvalue !== previous option's textvalue, do...
        if (sel !== cache) {
            console.log('Option "' + sel + '" selected');  
        // else if it is the same, do...               
        } else {
            console.log('You selected the same option!!');
        }
        // update the cached option with the current option for subsequent checks
        cache = sel;
        // reset count
        count--;
    } else {
        count++;
    }
});

Test HTML:

<select id="allLocationsDropDownTablet">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>

You can test this here (open console first).



来源:https://stackoverflow.com/questions/26243013/execute-function-when-selecting-same-option-in-select-html-tag

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