I'm having a problem in a simply js function. I have a web page where I show records in a table, and when I click on an icon (which stands for 'change this record'), that cell of table should be replaced with a dropdown menu in which the user can select the new value for that record based on the available ones.
I tried in a lot of ways:
function clickOnModifyProfessor(id, professors) {
let select = document.createElement("select");
select.setAttribute("id", id);
for (let i = 0; i < professors.length; i++) {
let el = document.createElement("option");
el.textContent = professors[i]['name'] + " " + professors[i]['surname'];
el.value = professors[i]['professorID'];
select.appendChild(el);
}
//I set id=2 simply to test with one specific record, if it works I'll just set another parameter to generalize the change.
const node = document.getElementById("2");
node.textContent = '';
node.appendChild(select);
}
With this code I just get the empty table cell after clicking on the modify button, but the strange thing is that if I try to create another element (textarea, password etc) it works perfectly, so I can't understand why it does this only with the select element. I also tried by creating the whole select with option elements and taking it to the table cell by the innerHTML, but it doesn't works (as before, it works with others elements that aren't 'select').
If it can help, here is the code fragment where I call this function:
echo "<tr><td>" . $row['subjectName'] . "</td>
<td id='" . $rowsCount . "'>
<p>" . $row['profName'] . " " . $row['profSurname'] . "
<i class='material-icons' onclick='clickOnModifyProfessor(" . json_encode($row['subjectName'], JSON_HEX_APOS) . "," . json_encode($professors, JSON_HEX_APOS) . ")'>create</i>
</p>
</td>
</tr>";
PS: I also tried to print in console document.getElementById(id).innerText after I append the new 'select' element to the document and it prints correctly the options I added.
Am I making an error? I hope it's sufficiently clear.
I answer my own question with the solution I found, maybe it can be helpful for someone.
The problem is that the materialize css' select can't render on browser without starting js before, so it's necessary to add class='browser-default' when we create the select element or, if we want materialize css select style, we need to use $('select').formSelect(); after the select element has been created with its options.