简体   繁体   English

如何更改 select 选项文本

[英]How to change select option text

在此处输入图像描述 When I set the has-empty-data=true attribute for the select tag, an empty option will be added to the list option.当我为 select 标签设置 has-empty-data=true 属性时,列表选项中将添加一个空选项。 so how can I set the text for this empty option tag?那么如何设置这个空选项标签的文本呢?

<select name="address[province]" title="{{ 'customer.addresses.province' | t }}" has-empty-data="true" data-default="{{ form.province }}" id="provinceExist"></select>

在此处输入图像描述 I tried doing this but it still doesn't work我试过这样做但还是不行

document.getElementsByName('provinceExist').options[0].innerHTML = "Water";

You need to used getElementById instead of getElementByName as your field have id called provinceExist :你需要使用getElementById而不是getElementByName因为你的字段有id调用provinceExist

Also, you need to add ContentLoaded event for change text or you need to create function to call on event happen.此外,您需要为更改文本添加ContentLoaded事件,或者您需要创建 function 来调用事件发生。 I have taken Content loaded event as an example.我以内容加载事件为例。

    window.addEventListener("DOMContentLoaded", () => {
        document.getElementById("provinceExist").options[0].text = "Water";
    });

Here example select box:此处示例 select 框:

<select name="address[province]" id="provinceExist">
  <option>Test</option>
  <option>Test1</option>
  <option>Test2</option>
</select>

You can try using the text property of the Option object:您可以尝试使用 Option object 的文本属性:

document.getElementsByName('provinceExist').options[0] = new Option('Water', '');

You can also use the innerHTML property to set the text for the empty option tag, like this:您还可以使用innerHTML属性设置空选项标签的文本,如下所示:

document.getElementsByName('provinceExist').options[0].innerHTML = 'Water';

getElementsByName returns a collection of elements, so you need to access the first element in the collection to be able to set the innerHTML or text property. getElementsByName返回元素集合,因此您需要访问集合中的第一个元素才能设置innerHTML或文本属性。

document.getElementsByName('address[province]').options[0].innerHTML = "Water";

instead of代替

document.getElementsByName('provinceExist').options[0].innerHTML = "Water";

or if you want to use the id you could use或者如果你想使用你可以使用的 id

document.getElementsById('provinceExist').options[0].innerHTML = "Water";

there's also another neatway instead of having to go through all this还有另一个 neatway 而不是必须通过所有这些 go

<select>
<option hidden disabled selected value> -- select an option -- </option>


  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select>

this will show up -- select an option -- and once you select something this option won't no longer exist and you won't be able to select it back/view it again这将显示-- select an option --一旦你 select 这个选项将不再存在并且你将无法 select 它返回/再次查看

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

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