How to change the text of Select2 using jQuery?
For changing the text of Select2 library is always a tricky part. I searched a lot of how to figure this out. on the first occasion I was juggling with Jquery to change the text of select tag. Every time one thing is missing. I wrote more than 30 lines of codes and spend more than 3 hours to figure this out. But didn’t got any success. Finally, I started from scratch and looking for the possible way of changing select tag text. So finally, I came across these three lines of code to figure this out.
You will need to grab the select tag id and insert in this code, and enter the values you needed to change, and that’s it.
jQuery("#select-id").find("option:nth-child(1)").text('Yes'); jQuery("#select-id").find("option:nth-child(2)").text('No'); jQuery("#select-id select").trigger("change");
In first two lines, we grab the change the text of option tag. Finally, we call trigger to change the text of select2 tag.