rwkiii rwkiii - 3 months ago 50
jQuery Question

How to change all <option> Text in SelectPicker

I need to change the text in all

<option ...> ... </option>
elements of a dropdown that uses jQuery SelectPicker. None of the values should be effected.

Initially, when the options are populated there is a placeholder of
in the option text. For example:


All of the option texts have this similar format. I need to iterate through each option text, change the
value and save the change.

The change is dependent on another control which could change back and forth, but the
is obviously gone after the first change. So I thought I could save the initial
in document.ready:

_savedSelect = $('#mySelect');

At this point I can iterate through _savedSelect when needed, read the default texts containing the
placeholders, modify each and then save them to the
elements of the actual

After modifying all texts:


But I'm not sure how to iterate all options in the saved select, get the text of each, replace the
placeholder and then save it to the actual select options.

Could anyone give me an idea on how to do this?


I've worked out part of the .each:

$("#mySelect > option").each(function () {
$newtext = HOW TO GET CORRESPONDING TEXT FROM _savedSelect??;
this.text = $newtext.replace( 'XX', $('#someInput').val() );


How do I get the corresponding text value from the saved select?


One of @madalinivascu's answers works somewhat, but not completely:

$("#mySelect> option").each(function () {
$textarr = $(this).text().split('XX');
$newtext = $textarr[0] + $('#someInput').val() + $textarr[1];

But this will only work the first time the input control is changed since
gets replaced. In my description above I mentioned saving the initial state of
in a variable. This way I will always have the text strings with placeholders in them - my problem is I don't know how to access the text values inside of the saved variable.


Try the following, clone the select after page load, loop it and based on the value of cloned element change the on page elements text to the desired text

$cloned = $("#mySelect").clone();

 $cloned.find('option').each(function () {
    $textarr= $(this).text().split('XX');

    $newtext =  $textarr[0]+$('input').val()+$textarr[1];
    $("#mySelect > option[value='"+$(this).val()+"']").text($newtext);