The user is able to create rows in an HTML table dynamically by setting the number of hours they want to work with. This was achieved with Javascript.
For example, if the user types in the number 5, 5 rows will show in the table.
How do I use my model with dynamic components?
I've tried adding this inside the script:
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control", id = "priceInput", type = "number" } })
Instead of:
const priceInput = document.createElement('priceInput');
Check the full script below.
<script type="text/javascript">
function changeRow() {
const aTable = document.getElementById('hourPriceTable');
const hourTextBox = document.getElementById('hourInput');
const rowNumber = parseInt(hourTextBox.value);
if (rowNumber) {
const rows = [];
for (let i = 1; i <= rowNumber; i++) {
if (rowNumber < 1 || rowNumber > 24) {
document.getElementById('error').innerText = ('O número de horas precisa de ser entre 1 e 24.');
document.getElementById('error').style.color = 'red';
return false;
} else {
document.getElementById('error').innerText = '';
}
const row = document.createElement('tr');
const th = document.createElement('th');
const td2 = document.createElement('td');
th.setAttribute("class", "text-center");
td2.setAttribute("class", "text-center");
const priceInput = document.createElement('priceInput');
priceInput.type = 'number';
priceInput.setAttribute("class", "text-center");
th.append(i);
td2.append(input);
row.append(th);
row.append(td2);
rows.push(row);
}
aTable.innerHTML = "";
rows.forEach(row => aTable.append(row));
}
}
</script>
I'd like the model I'm using to work with the data (storing to database) inserted in these dynamic rows since they have text boxes inside. I've been struggling with adding this functionality as I can't use Html.EditorFor to create the text boxes inside the JavaScript code.
Html.EditorFor) and generates the HTML. The client browser renders the HTML and executes the JavaScript. Note that there is a strict separation of execution contexts and that everything (and only things) that end up on the HTML (or JavaScript resource, eg.) "by some method" can be used on the client.