简体   繁体   中英

Execute function when selecting same option in select html tag

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>

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM