Reputation: 567
I have a project creating select boxes for a client. But he is asking for something I'm not familiar with. Basically for every option in the select box he wants to add additional text to it. For example if this option is selected: <option value="all">all</option>
it would come out like this "category: all". I am able to change the first option that is selected but I need to be able to change each option when it gets selected from the dropdown. I believe Im close to the solution, just missing something. Most likely a change function. Any suggestions would be appreciated
jquery
$(function () {
var selected = $('#selectBox');
var optionName = $(selected).find("option:selected").text();
$(selected).find("option:selected").html('<span>category:</span> '+optionName+'');
console.log(selected);
});
html
<select id="selectBox" name="selectBox">
<option value="all">all</option>
<option value="milk">milk</option>
<option value="frozen">frozen</option>
<option value="cream">cream</option>
<option value="sour-cream">sour cream</option>
<option value="cottage-cheese">cottage cheese</option>
<option value="eggnog">eggnog</option>
<option value="calorie-counter">calorie countdown</option>
<option value="juices-drinks">juices & drinks</option>
<option value="simply-smart">simply smart</option>
<option value="our-farmers">our farmers</option>
</select>
Upvotes: 2
Views: 1256
Reputation: 253308
I'd suggest:
// select the select elements (amend to your use-case)
$('select')
// binding an anonymous function as an event handler to the 'change' event:
.on('change', function(){
// this is the 'select' element
$(this)
// find the 'option' elements inside that select:
.find('option')
// iterating over each element within the 'text()' method:
.text(function(i,t){
// i: is the index of the current element,
// t: is the current text (before manipulation)
// if the current option is 'selected' we prepend the text with 'Category: '
// if not, we remove 'Category: ' (if it's there)
return this.selected ? 'Category: ' + t : t.replace('Category: ', '');
});
// trigger the change event, causing the handler to fire (so 'Category: ' is
// prepended to the default-shown 'option' text on page-load:
}).change();
References:
Upvotes: 6