How to set selected value of jquery select2?

后端 未结 28 1464
野趣味
野趣味 2020-11-30 00:00

This belong to codes prior to select2 version 4

I have a simple code of select2 that get data from ajax



        
28条回答
  •  孤街浪徒
    2020-11-30 00:41

    Nice and easy:

    document.getElementById("select2-id_city-container").innerHTML = "Your Text Here";
    

    And you change id_city to your select's id.

    Edit: After Glen's comment I realize I should explain why and how it worked for me:

    I had made select2 working really nice for my form. The only thing I couldn't make work was to show the current selected value when editing. It was searching a third party API, saving new and editing old records. After a while I realized I didn't need to set the value correctly, only the label inside field, because if the user doesn't change the field, nothing happens. After searching and looking to a lot of people having trouble with it, I decided make it with pure Javascript. It worked and I posted to maybe help someone. I also suggest to set a timer for it.

提交回复
热议问题