简体   繁体   中英

Chosen jQuery framework select option from dropdown with Javascript

I'm using the Chosen jQuery framework with a basic select statement.

I use the following line of code to open the dropdown:

$('#<id-of-your-select>_chzn').trigger('mousedown');

That statement opens the Chosen dropdown.

选择下拉菜单

Then I want to select the top item which is a li element with the id: pt_chzn_o_1.

I've tried the following, but none of them will select the option.

$('#pt_chzn_o_1').trigger('mousedown');
$('#pt_chzn_o_1').click();

How do you select an option using Javascript/jQuery as if I clicked the top option with my mouse.

Why don't you just change the selected index instead? It seems like you are trying to achieve the same thing but go about it in the "human way" as oppose to the "programming way", like so:

$('#<id-of-your-select>').val('value-of-pt_chzn_o_1').trigger('chosen:updated');

Make sure to change both the jQuery selector and the value to match your circumstances.

This is what ended up working for me:

The initial click triggers an event to show additional fields(optional, only needed in my specific case).

$("#<id-of-your-select>_chzn").trigger("click")

This statement opens the Chosen dropdown:

$("#<id-of-your-select>_chzn").trigger("mousedown")

Execute this statement on the li element id of the chosen dropdown element you want to choose.

$("#pt_chzn_o_1").trigger("mouseup")

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