Html option caption

Whing Dela Cruz
Whing Dela Cruz used Ask the Experts™
on
Hi, Experts, How to change the option caption using javascript? Base on my code, I want to change the option caption from "Yes" to "No". Thanks!

<!DOCTYPE html>
<html>
<body>
<button onclick="return ChangeCaption()">Change</button>
<select name="level" id="iAD8" style="color: black; width:50px;">
    <option value="yes" selected>Yes</option>
    <option value="no">No</option>
</select>

<script>
function ChangeCaption()
{
  document.getElementById("iAD8").value = "No"; 
}
</script>

</body>
</html>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Analyst Developer
Distinguished Expert 2018
Commented:
You was so close, you need just to use the value instead of the text so replace  `No` by `no` :

document.getElementById("iAD8").value = "no";

Open in new window


Working fiddle

As a best practice I would suggest to you the use of `.addEventListener()` to attach events instead of inline event `onclick` :

<html>

  <body>
    <button id="my-button">Change</button>
    
    <select name="level" id="iAD8" style="color: black; width:50px;">
        <option value="yes" selected>Yes</option>
        <option value="no">No</option>
    </select>

    <script>
      document.getElementById("my-button").addEventListener('click', function() {
        document.getElementById("iAD8").value = "no";
      })
    </script>
  </body>

</html>

Open in new window

Author

Commented:
Perfectly working, thanks a lot sir!
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
You're welcome, glad to help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial