0

So, i´m trying to change a text for an option with jquery.

HTML

<select id="mySelect"> <option value="change me">Change me</option> </select> 

JS

$(document).ready(function() { $('#mySelect').select2(); $(document).find('option[value="change me"]').text('Changed'); }) 

Well, nothing happends.
It´s important to change the text "live".
Fiddle: https://jsfiddle.net/gmt22ffL/2/

Is this even possible?
I´m using Jquery plugin "Select2" for my select.

1

1 Answer 1

1

It works perfectly fine. But let's try adding Select2 and see:

$(document).ready(function() { $('option[value="change me"]').text('Changed'); $('#mySelect').select2(); });
<script src="https://code.jquery.com/jquery-1.11.3.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.full.min.js"></script> <select id="mySelect"> <option value="change me">Change me</option> </select>

Swapping the lines work.

Destroying and changing:

$(document).ready(function() { $('#mySelect').select2(); $('#mySelect').select2("destroy"); $('option[value="change me"]').text('Changed'); $('#mySelect').select2(); });
<script src="https://code.jquery.com/jquery-1.11.3.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.full.min.js"></script> <select id="mySelect"> <option value="change me">Change me</option> </select>

Sign up to request clarification or add additional context in comments.

4 Comments

oh, easy fix. I like that =) Thank you!
Of corse, im waiting for it... I do have a new problem. In my actually code i load select2 way before this code runs. Is there away to unset Select2 and then add it again so that i can run this code. It seams like Select2 don´t like "Text changing" code?!
@Mjukis Lemme try both. Loading and changing, and also destroy, change and load.
@Mjukis To change the code dynamically: github.com/select2/select2/issues/2830

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.