hwhat
hwhat

Reputation: 356

Creating <select> with onchange and eventListener

How would I take this:

<select onchange='disable(this)'> //options here  </select>

and make it into a createElement and eventListener? I don't know how to add the onchange="disable(this)".

So far I have:

var optionList = ["default", "yes", "no"];

var td = document.createElement("td");
selectList = document.createElement("select");
selectList.addEventListener("change", lockSelect, false);
td.appendChild(selectList);
newTableRow.appendChild(td);

for (var j = 0; j < optionList.length; j++)
{
   option = document.createElement("option");
   option.value = optionList[j];
   option.text = optionList[j];
   selectList.appendChild(option);
 }

This makes the <select> and <options>, but I cant figure out how to make the onchange=disable(this)

Upvotes: 1

Views: 54

Answers (1)

synthet1c
synthet1c

Reputation: 6282

You need to create a function for lockSelect. You have not show the function for disable so I have to guess.

lockSelect should call disable passing the event target element to it.

It might be better to just change the disabled function to operate on an event object instead. and pass that directly to the event listener.

function disable(e) {
  e.target.disabled = true
}

var optionList = ["default", "yes", "no"];
var newTableRow = document.querySelector('tr')

function disable(element) {
  element.disabled = true
}

function lockSelect(e) {
  disable(e.target)
}

var td = document.createElement("td");
selectList = document.createElement("select");
selectList.addEventListener("change", lockSelect, false);
td.appendChild(selectList);
newTableRow.appendChild(td);

for (var j = 0; j < optionList.length; j++) {
  option = document.createElement("option");
  option.value = optionList[j];
  option.text = optionList[j];
  selectList.appendChild(option);
}
<table>
  <tr></tr>
</table>

Upvotes: 1

Related Questions