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.

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.

有帮助吗?

解决方案 2

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top