Here's how it's supposed to work. By default there are two sets of input fields where the percentage fields have a value of 50% each. Now whenever a new input field is added, the percentage field value should be divided between all of them, for example, if there are 3 sets then percentage fields should have 33.33% each. If there are 4 then 25% each.
The issue right now is whenever I add a new field, percentage is not divided the first time but then I add another field and that is when it is divided among all the fields except the new one.
Another issue is, if I delete one then the percentage doesn't reduce. It stays the same.
Please note that in the javascript code, I had to declare percInput variable twice, once outside the click event and once inside the click event. This is because the default fields must have 50% allocated to each before adding new fields. And this is the only way I could allocate it dynamically, although I could hardcode it in html.
Here's what I tried so far:
const form = document.querySelector("form");
const span = document.querySelector("span");
const addBtn = document.querySelector("#addField");
const html = `
<div class="url-pair">
<input type="url" placeholder="3">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
`;
let percInput = document.querySelectorAll('.urls-container .perc');
let percentage = (100 / percInput.length).toFixed(2).toString() + "%";
percInput.forEach((item) => {
item.setAttribute("value", percentage);
});
const removeField = (e) => {
if (!e.target.classList.contains('delete-btn')) return;
e.target.parentElement.remove();
}
// delete field
form.addEventListener('click', removeField);
// add field and divide input value automatically
addBtn.addEventListener('click', () => {
percInput = document.querySelectorAll('.urls-container .perc');
percentage = (100 / percInput.length).toFixed(2).toString() + "%";
percInput.forEach((item) => {
item.setAttribute("value", percentage);
});
span.insertAdjacentHTML("beforeBegin", html);
});
<form action="#" method="POST">
<div class="urls-container">
<div class="url-pair">
<input type="url" placeholder="1">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
<div class="url-pair">
<input type="url" placeholder="2">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
<span></span>
</div>
<div>
<div>
<button type="button" id="addField">Add Field</button>
</div>
<div>
<button type="submit">Create</button>
</div>
</div>
</form>