Reputation: 17
I want to insert the value of a multiselect option form into the same table cell.
The select form is inside a table so I get the select value using const selectThing = [...document.getElementById('tableIdName').querySelectorAll("#selectIdName :checked")]
This works so far.
So:
I just cannot figure out what the right code is.
Feel free to check out the code!
function add() {
const inputs = [...document.getElementById('inputs').querySelectorAll("input")];
const selectFruit = [...document.getElementById('inputs').querySelectorAll("#fruit :checked")];
if (isFormValid(inputs)) {
const table = document.getElementById('table')
const newRowIdx = table.rows.length
const rowId = `row_${newRowIdx}_${Date.now()}`
const row = table.insertRow(newRowIdx)
row.id = rowId
inputs.forEach((input, idx) => {
const cell = row.insertCell(idx)
cell.appendChild(formatInputValue(input))
})
selectFruit.forEach((input, idx) => {
const cell = row.insertCell()
cell.appendChild(formatInputValue(input))
})
const actions = {
Delete: () => {
const row = document.getElementById(rowId)
row.parentNode.removeChild(row)
}
}
const actionCell = row.insertCell()
actionCell.appendChild(formatActionButtons(actions))
resetInputs(inputs)
}
}
function formatInputValue(input) {
return document.createTextNode(input.value)
}
function formatActionButtons(buttons) {
const wrapper = document.createElement('div')
Object.entries(buttons).forEach(([action, onclick]) => {
let button = document.createElement('button')
button.innerText = action
button.onclick = onclick
button.id="jsButtonStyle";
wrapper.appendChild(button)
})
return wrapper
}
function isFormValid(inputs) {
return inputs.filter(input => input.value === "").length === 0
}
function resetInputs(inputs) {
inputs.forEach(input => input.value = "")
}
<table id="inputs">
<tr>
<th><label>Name:*</label></th>
<th><label>Fruit:*</label></th>
</tr>
<tr>
<td><input type="text" id="name" required></td>
<option value="" selected disabled>Choose Fruit</option>
<td><select type="text" id="fruit" multiple required>
<option value="" selected disabled>Choose Fruit</option>
<option>Apple</option>
<option >Plum</option></select>
</td>
</tr>
</table>
<div>
<button id="button" onclick="add()">Add</button>
</div>
<div>
<h2>Here:</h2>
<table id="table" border="2">
<tr>
<th>Name</th>
<th>Fruit</th>
</tr>
</table>
</div>
Upvotes: 0
Views: 775
Reputation: 1638
Moving row.insertCell()
outside of a loop should solve as you only need one cell for selectFruit
.
...
const cell = row.insertCell();
let arr = [];
selectFruit.forEach((input, _) => arr.push(input.value));
const textNode = document.createTextNode(arr.join(","));
cell.appendChild(textNode);
...
Upvotes: 0