user20942136
user20942136

Reputation:

How to change select option text

enter image description here When I set the has-empty-data=true attribute for the select tag, an empty option will be added to the list option. 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>

enter image description here I tried doing this but it still doesn't work

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

Upvotes: 0

Views: 81

Answers (3)

Hardik Solanki
Hardik Solanki

Reputation: 3195

You need to used getElementById instead of getElementByName as your field have id called provinceExist:

Also, you need to add ContentLoaded event for change text or you need to create function to call on event happen. I have taken Content loaded event as an example.

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

Here example select box:

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

Upvotes: 1

Ahmad ghoneim
Ahmad ghoneim

Reputation: 929

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

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

there's also another neatway instead of having to go through all this

<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

Upvotes: 0

Nemus
Nemus

Reputation: 3995

You can try using the text property of the 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:

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.

Upvotes: 0

Related Questions