Javascript – jQuery trigger click (or select) on chosen dropdown option

htmljavascriptjqueryjquery-chosen

I'm trying to trigger a click function on page load with jQuery on chosen's dropdown option so that the follow-up action can take place but haven't been able to get it work.

I've tried:

jQuery("document").ready(function() {
setTimeout(function() {
    jQuery("customlist_chzn_o_2").trigger('click');
},10);

or

jQuery("document").ready(function() {   
    jQuery('#customlist').val(9).trigger("chosen:updated")  
});

or

jQuery("document").ready(function() {   
    jQuery('#customlist_chzn_o_2').trigger("chosen:updated")    
});

None of them are working, please note that my select's id is #customlist the id of dropdown element in chosen which I need to click is #customlist_chzn_o_2 and the value of the select option is 9

Best Answer

If I understand you correctly, you need to trigger the change event on the original select, not on the custom or his options.

When working with form fields, you often want to perform some behavior after a value has been selected or deselected. Whenever a user selects a field in Chosen, it triggers a "change" event on the original form field

But when you change the original select value, than you should trigger chosen:updated.

If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

https://harvesthq.github.io/chosen/#change-update-events

var sel1 = $('#sel1').chosen({width: '150px'}).change(function(){
  console.log($(this).val());
});

sel1.trigger('change');

var sel2 = $('#custom_field').chosen({width: '150px'});

//$('button').click(function() {
$(document).ready(function() {
  sel2.val('9');
  
  // Than you should trigger the "chosen:updated"
  sel2.trigger('chosen:updated');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.min.css" rel="stylesheet"/>

<select id="sel1">
  <option>option 1</option>
  <option>option 2</option>
  <option>option 3</option>
</select>
<hr />
<select id="custom_field">
  <option>option 1</option>
  <option>option 2</option>
  <option>9</option>
</select>

<button>Set custom_field's value to "9"</button>