简体   繁体   English

如何动态更新选择值?

[英]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 HTML代码

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

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/ 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/ https://jsfiddle.net/r5377h21/1/

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM