Reputation: 43
I have this form, and I need to convert the list items to inputs so I can submit them via POST. I've tried to append to each list items a hidden input. Here's my code:
function add() {
let ul = document.getElementById('basket-list');
let li = document.createElement('li');
let item = document.getElementById('code-input');
// Here I try to append an hidden input, but it's not working
let input = document.createElement('input')
input.setAttribute("type", "hidden");
input.setAttribute("name", "name");
input.setAttribute("value", "value");
//li.appendChild(document.createTextNode(input));
//item.appendChild(document.createElement('input'));
ul.appendChild(li);
console.log(ul);
let lis = document.getElementById('basket-list').childNodes;
let list = [];
for( let i = 1; i < lis.length; i++ ){
let li = lis[i];
list.push(li.textContent);
}
console.log(list);
}
<form action="">
<ul id="basket-list">
</ul>
<div class="basket-inputs">
<input type="text" class="code-input" id="code-input" name="code-input" placeholder="Código">
<button type="button" onclick="add()" ><i class="fas fa-check">Add</i></button>
</div>
</form>
Upvotes: 0
Views: 564
Reputation: 15847
For testing purposes, I used text
elements instead of hidden.
The two big things is, appending the input
and appending the text node of item.value so you can see the text that was added.
li.appendChild(input);
li.appendChild(document.createTextNode(item.value));
function add() {
let ul = document.getElementById('basket-list');
let li = document.createElement('li');
let item = document.getElementById('code-input');
// Here I try to append an hidden input, but it's not working
let input = document.createElement('input')
input.setAttribute("type", "text");
input.setAttribute("name", "name");
input.setAttribute("value", item.value);
li.appendChild(input);
li.appendChild(document.createTextNode(item.value));
ul.appendChild(li);
let lis = document.getElementById('basket-list').childNodes;
let list = [];
for( let i = 1; i < lis.length; i++ ){
let li = lis[i];
list.push(li.textContent);
}
console.log(list);
}
<form action="">
<ul id="basket-list">
</ul>
<div class="basket-inputs">
<input type="text" class="code-input" id="code-input" name="code-input" placeholder="Código">
<button type="button" onclick="add()" ><i class="fas fa-check">Add</i></button>
</div>
</form>
Upvotes: 1