Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change string in select option

I have a problem in html document.

I want to replace "pikusadrian" with "Adrian Pikus"

Why does my script not work?

var text = document.getElementById("user").innerHTML;
if (text == "pikusadrian") {
  document.getElementById("user").textContent = "Adrian Pikus";
}
<select type="text" class="form-control" name="operator" placeholder="operator" required />
<option selected><span id="user">pikusadrian</span></option>
like image 221
Blimer Avatar asked Jun 17 '26 18:06

Blimer


1 Answers

Invalid HTML - you close the select and have invalid spans in the options

This works

[...document.querySelectorAll("#operator option")].forEach(opt => {
  if (opt.text == "pikusadrian") opt.text = "Adrian Pikus";
})
<select type="text" class="form-control" name="operator" id="operator" placeholder="operator" required>
  <option selected>pikusadrian</option>
</select>

This MIGHT work, but normally options do not have IDs

const opt = document.getElementById("user");
if (opt.text === "pikusadrian") opt.text = "Adrian Pikus";
<select type="text" class="form-control" name="operator" id="operator" placeholder="operator" required>
  <option selected id="user">pikusadrian</option>
</select>
like image 99
mplungjan Avatar answered Jun 20 '26 08:06

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!