Home > Net >  How to change the button name in a dropdown button list to replace the very first one button
How to change the button name in a dropdown button list to replace the very first one button

Time:02-24

I am currently doing a dropdown button and I would like to change the button text to the certain one when user click on it for example when user click on English, the very first button will change to the text English and so on. I have try the method below but it didn't works.

Below is my HTML code:

       <div >
          <button
            onclick="myFunction();hideBorder();change()"
            
            id="chi"
          >
            CHINESE
          </button>
          <div id="myDropdown" >
            <button id="eng">ENGLISH</button>
            <button id="fre">FRENCH</button>
            <button id="ger">GERMAN</button>
            <button id="ita">ITALIAN</button>
            <button id="mal">MALAY</button>
            <button id="spa">SPANISH</button>
          </div>
        </div>

Below is my JavaScript code:

function change() {
  var btn1 = document.getElementById("chi");
  var btn2 = document.getElementById("eng");
  if (btn2.onclick) {
    btn1.value = "ENGLISH";
  }
}

This is the example of my dropdown button: dropdown button

CodePudding user response:

Use btn1.innerHtml or btn1.innerText instead of btn1.value. As you are using buttons, the text is actually not the value, but a child node. If you were using <input type="button"/> your code would work aswell, as on input buttons the value is used as text.

I am kind of confused why you added if (btn2.onclick) { to your code. You don't have an eventlistener for your btn2. Therefore that query will always be false (and text not changed), as btn2.onclick is undefined.

CodePudding user response:

.dropdown-content {width:150px;}
<div >

          <select id="myDropdown" >
            <option id="chi">CHINESE</option>
            <option id="eng">ENGLISH</option>
            <option id="fre">FRENCH</option>
            <option id="ger">GERMAN</option>
            <option id="ita">ITALIAN</option>
            <option id="mal">MALAY</option>
            <option id="spa">SPANISH</option>
          </select>
        </div>

I'm assuming you want something like this.

.dropdown-content {width:150px;}
     <div >

          <select id="myDropdown" >
            <option id="chi">CHINESE</option>
            <option id="eng">ENGLISH</option>
            <option id="fre">FRENCH</option>
            <option id="ger">GERMAN</option>
            <option id="ita">ITALIAN</option>
            <option id="mal">MALAY</option>
            <option id="spa">SPANISH</option>
          </select>
        </div>
  • Related