Question

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.

Was it helpful?

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top