skip to Main Content

I have some code that displays a series of buttons on a website.

 <input id="btnDay1" class="daybtn" type="button" value="Day 1" onclick="displayGraphicxxx (Day1)"</input>
 <input id="btnDay2" class="daybtn" type="button" value="Day 2" onclick="displayGraphicxxx (Day2)"</input>

I need to have the page update the buttons when a user selects a different option to:

 <input id="btnDay1" class="daybtn" type="button" value="Day 1" onclick="displayGraphicyyy (Day1)"</input>
 <input id="btnDay2" class="daybtn" type="button" value="Day 2" onclick="displayGraphicyyy (Day2)"</input>

I understand that .innerHTML will not work in this case, and when I tried using .value instead, nothing was changed. How can I change the onclick section programmatically?

2

Answers


  1. I suggest you delegate to the closest common container (calendar div?) and use an event listener

    Also your HTML was invalid

    const displayXXX = str => console.log("xxx",str);
    const displayYYY = str => console.log("yyy",str);
    document.getElementById("buttonDiv").addEventListener("click", (e) => { // any click in the div
      const tgt = e.target;
      if (!tgt.matches(".daybtn")) return; // not a button
      const version = document.getElementById("whichVersion").value; // value of the select
      if (version === "xxx") displayXXX(tgt.value); 
      else if (version === "yyy") displayYYY(tgt.value);
    })
    <select id="whichVersion">
      <option value="">Please select</option>
      <option value="xxx">xxx</option>
      <option value="yyy">yyy</option>
    </select>
    <div id="buttonDiv">
      <input id="btnDay1" class="daybtn" type="button" value="Day 1" />
      <input id="btnDay2" class="daybtn" type="button" value="Day 2" />
    </div>
    Login or Signup to reply.
  2. Here you are a way you could do that. It is simple for your case.

    .setAttribute gets two props:

    • the name of the attribute
    • the value that is going to be assigned
    document.getElementById("btnDay1").setAttribute("onclick", "displayGraphicyyy (Day1)")
    document.getElementById("btnDay2").setAttribute("onclick", "displayGraphicyyy (Day2)")
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search