Reputation: 3
Can anyone please help me how to accomplish following?
I have a dropdown field, which have flowers name.The default value is "Select your favorite flower". On tap or click, the dropdown opens and shows the list of options and when user selects a particular value, the field shows the selected flower name.
I need to append Favorite Flower: then the selected value. Can you guys please help me in how to accomplish this?
Please see the image:
<select>
<list> Select your favorite flower</list>
<list>Rose</Rose> <list>Marigold </list>
<list>Lily</lily>
</select>
Upvotes: 0
Views: 262
Reputation: 32354
Use a change event, append a span with the text to the selected option:
$('select').on('change',function() {
$('option').find('span').remove();//remove previous selected span
var val = $(this).find(':selected').html();//get the text/html of the potion
$(this).find(':selected').html('<span>Favorite Flower: </span>'+val);//change the text with the option
});
https://jsfiddle.net/r5377h21/
or:
$('select').on('change',function() {
$('option').find('span').remove();
var selected = $(this).find(':selected'),
val = selected.html();
if(!selected.is('option:first')) {
$(this).find(':selected').html('<span>Favorite Flower: </span>'+val);
}
});
https://jsfiddle.net/r5377h21/1/
Upvotes: 1
Reputation: 1996
can you please try this.
let me know if you need any changes in it
Code :
<script>
function test(obj)
{
$("select option").each(function(){
$(this).text($(this).text().replace("favorite flower - ",""))
})
if($("option:selected",$(obj)).val() != -1){
$("option:selected",$(obj)).text("favorite flower - "+$("option:selected",$(obj)).text())
}
}
</script>
<select onchange="test(this)">
<option value="-1">Select your favorite flower</option>
<option>Rose</option>
<option>Marigold</option>
<option>Lily</option>
</select>
Upvotes: 0