Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

jquery - Trigger a select form element to show its options (open drop down options list) with Javascript

Here is the markup

<select id="person_prefix" name="prefix">
 <option value=""></option>
 <option value="Dr" selected="selected">Dr</option>
 <option value="Mr">Mr</option>
 <option value="Ms">Ms</option>
 <option value="Mrs">Mrs</option>
</select>

and I want to trigger a javascript event so that the option list drops down. Using jquery I've tried the following:

$("#person_prefix").click();
$("#person_prefix").mousedown();
$("#person_prefix").change();

but nothing seems to work. Which event is this and how can be triggered?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was once searching how to do the same thing and didn't find any working solution but then a guy in our javascript group came with a clever work around. Here is the code.

HTML

<input type="button" id="show" value="show" />
<select id="myslect">
    <option>nothing</option>
    <option>something</option>
    <option>anything</option>
</select>

Javascript

$("#show").click(function () {
    var element = $("select")[0],
        worked = false;
    if(document.createEvent) { // chrome and safari
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        worked = element.dispatchEvent(e);
    }
    if(!worked) { // unknown browser / error
        alert("It didn't worked in your browser.");
    }
});

I'm not sure how to link to the group post so you can see the whole thread. Anyway credits to CJ Madolara. Good Job!

Update: Only works on Chrome and Safari


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...