Björn C
Björn C

Reputation: 4008

Change text for `option` in a `select` with jquery

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.

Upvotes: 0

Views: 56

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

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>

Upvotes: 1

Related Questions