The problem you are facing is that MaterializeCSS needs the M.Autocomplete.init() function to be called after the input elements are created,
so that autocomplete is correctly initialized on new table elements. Additionally, you must ensure that each input element has a unique id.
Here is a revised version of your code to fix these issues:
<table border="1" id="tableData" class="#eeeeee grey lighten-3" style="width:90%; margin: 0px auto; align: center;">
<thead>
<tr>
<th colspan="3">Static autocomplete for test purposes:</th>
</tr>
<tr>
<th>Job</th>
<th>namen</th>
<th>Please select project:</th>
</tr>
</thead>
<tbody id="table-body">
<tr>
<td>
<div class="input-field">
<input type="text" id="autocomplete-input-static" class="autocomplete">
<label for="autocomplete-input-static"></label>
</div>
</td>
</tr>
</tbody>
</table>
</div>
JavaScript:
<script>
//EVENTS
window.addEventListener('load', () => {
loadingData();
});
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.autocomplete');
var instances = M.Autocomplete.init(elems, {
data: {
'option 1': null,
'option 2': null,
'option 3': null
},
minLength: 0
});
});
//FUNCTIONS
function loadingData() {
//just loading rotating thing
}
function generateTable(dataArray) {
console.log("generateTable");
var tbody = document.getElementById("table-body");
// Clear existing rows
tbody.innerHTML = '';
dataArray.forEach(function(r, index) {
var row = document.createElement("tr");
var col1 = document.createElement("td");
col1.textContent = r[0];
row.appendChild(col1);
var col2 = document.createElement("td");
col2.textContent = r[1];
row.appendChild(col2);
var col3 = document.createElement("td");
var div = document.createElement("div");
div.setAttribute("class", "input-field");
col3.appendChild(div);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", `autocomplete-input-${index}`);
input.setAttribute("class", "autocomplete");
div.appendChild(input);
var label = document.createElement("label");
label.setAttribute("for", `autocomplete-input-${index}`);
div.appendChild(label);
row.appendChild(col3);
tbody.appendChild(row);
});
// Initialize the autocomplete for new elements
var elems = document.querySelectorAll('.autocomplete');
var instances = M.Autocomplete.init(elems, {
data: {
'option 1': null,
'option 2': null,
'option 3': null
},
minLength: 0
});
console.log(tbody);
}
</script>
Explanation of changes:
Unique ID for Autocomplete: In generateTable, each autocomplete input receives a unique id, based on the row index.
Resetting Autocomplete: After creating new elements in the table, reset autocomplete for these elements.
Table Cleaning: Use tbody.innerHTML = ''; to clear all lines before adding new ones.
These changes should fix the issue and allow autocomplete to work correctly on dynamically generated table elements.