I tried this code from stackoverflow users and it works fine however I have few questions about it. How can I add the current selected option when the page is load? and instead of appending to the right, how can I make it on left? It looks like this "current:option 1".
jQuery('.getcatdishes').change(function(){
var valu = jQuery(this).val();
var text = jQuery(this).find('option:selected').text();
text += ' (current)';
jQuery(this).find("option:contains('current')").each(function(){
var txt = jQuery(this).text().replace('(current)','')
jQuery(this).text(txt);
});
jQuery(this).find('option:selected').text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="getcatdishes">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
Thanks guys
Without JQuery and using event delegation. The function to handle the current selected option can be called from everywhere, so it's used in the event handler and to display the selected option on document load.
document.addEventListener(`change`, evt => {
const fromSelector = evt.target.closest(`.getcatdishes`);
return fromSelector ? setCurrent(fromSelector) : true;
});
// set currently selected (if applicable)
setCurrent(document.querySelector(`.getcatdishes`));
function setCurrent(selector) {
[...selector.options].forEach(el =>
el.textContent = el.selected ?
`(current) ${el.textContent}` :
el.textContent.replace(`(current) `, ``));
}
<select class="getcatdishes">
<option>option 1</option>
<option>option 2</option>
<option selected>option 3</option>
</select>