Zohdi R
Zohdi R

Reputation: 3

How to dynamically update select value?

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:

All three states of dropdown

HTML Code

<select> 
  <list> Select your favorite flower</list> 
  <list>Rose</Rose> <list>Marigold </list>
  <list>Lily</lily> 
</select>

Upvotes: 0

Views: 262

Answers (2)

madalinivascu
madalinivascu

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

Dhaval Pankhaniya
Dhaval Pankhaniya

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

Related Questions