rwkiii rwkiii - 4 months ago 65
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
XX
in the option text. For example:

GHO.502/TT3-XX04-F.P1


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

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

_savedSelect = $('#mySelect');


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

After modifying all texts:

$("#mySelect").selectpicker('refresh');


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

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

EDIT

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() );
});

$("#mySelect").selectpicker('refresh');


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

UPDATE

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];
$(this).text($newtext);
});


But this will only work the first time the input control is changed since
XX
gets replaced. In my description above I mentioned saving the initial state of
#mySelect
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.

Answer

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();

$('input').on('change',function(){
 $cloned.find('option').each(function () {
    $textarr= $(this).text().split('XX');
    console.log($textarr);

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

demo:https://jsfiddle.net/egu3wo8k/1/

Comments