简体   繁体   中英

Attach onclick event to a dropdown with one element

I have a dropdown. Initially it is empty and at some point it is filled with elements dynamically. When the user choose an option the onchange event is triggered. This works when there are at least two values in the dropdown.

What I want to accomplish is, when there is only one element in the dropdown and the user clicks it, some event to be triggered. I tried the onclick event but this does not worked on the dropdown.

Here is my jsfiddle:

http://jsfiddle.net/MwHNd/551/

Some option may be to have defaut value like "Choose an option" in the dropdown and this way the onchange will always trigger. Is there are way to do it without this option?

well its not as simple as that, there are two aways you can go about doing this, both requires if statements.. you can either "dyamically" in js see how many options there are in a selector and tell it to change the element to a button OR do a focus function with jquery if there is only one element in your dropdown $selector.focus(function(){ then whatever you wants etc also you said you would not want to do this with a drop down. use a javascript function to click the event plus the selected index of the option values you want

function change(){
    document.getElementById("your-element").selectedIndex =2;
}
function changeit(){
    document.getElementById("your element").selectedIndex =1;
}
function changeitup(){
    document.getElementById("your element").selectedIndex =0;
}

so if you wanted the selected index plus the event you want to do

<input type='button' onclick="change();otherfunction()"> would give you the selected index plus the function you wanted originally

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