Modify Jquery Chosen select options dynamically.

Undoubtedly, every web developer would admit that Jquery Chosen plugin is a big time saver for them.  It's not only saving the time, but it takes out the whole pain of modifying and converting those ugly html select boxes into more usable elements. It is even simpler to use because all you have to do is tell the plugin to do the hard work for you, because this plugin wants only a simple select box to do its magic, be it either a single select or a multiple select.

Here I'm going to share something useful I came across recently with this plugin. I hope this will be useful for someone in future :) Most of the times, I used Chosen to display a static dropdown list only. It can be done with a few lines of Javascript easily. But this time, I was using the plugin in a small single page app written using Jquery. When the user adds a new item, the options in the select box has to be repopulated with the new one included.

Modify Jquery Chosen select options dynamically.




I went through the Chosen's documentation expecting to see some hints to get this done. Luckily I found this section.

Updating Chosen Dynamically

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.

$("#form_field").trigger("chosen:updated");

So this is what I wanted. And here is how I did this using Jquery. I appended the new item to the options list and triggered the chosen:updated as they have mentioned in the documentation.

var NewTopic = $('<option value="'+data.topic_id+'">'+data.topic_name+'</option>');
$('#choose-topics').append(NewTopic);
$('#choose-topics').trigger("chosen:updated");

This is a simple thing, but chances are there that someone might miss this specific part while reading the docs. That's why I wrote my own blog post too :)

Please do not forget to leave a comment if this blog post was useful to you. Also please share this with your friends in Google+, Facebook or Twitter if you think this will be useful to them.


5 comments :

  1. This comment has been removed by the author.

    ReplyDelete
  2. var ddlCustomers = $("[id*=ddlcatlogue]");

    ddlCustomers.trigger("chosen:updated")
    but not work

    ReplyDelete
    Replies
    1. ddlCustomers.Chosen(); //you forgot to initialize the select element with chosen.

      Just in case if someone is looking for the same issue

      Delete
  3. Thank you very much

    ReplyDelete