I am working off this example below (which works great) in order to add new items/fields within my form, on the fly depending on a drop down selection. Currently when the correct drop down is selected the correct div shows with the first input, however when I click add
, rather than adding an additional row (as works in my test code) with a new input, the page just reloads and the form is blank. I thought perhaps a conflict with another element on the page but haven't been able to find any culprit.
working example:
<div>
<label for="item">Enter a new item:</label>
<input type="text" name="item" id="item">
<button onclick="addItem()">Add item</button>
</div>
<ul>
</ul>
<script>
var list = document.querySelector('ul');
var input = document.querySelector('input');
var button = document.querySelector('button');
button.onclick = function() {
var myItem = input.value;
input.value = '';
var listItem = document.createElement('li');
var listText = document.createElement('span');
var listBtn = document.createElement('button');
listItem.appendChild(listText);
listText.textContent = myItem;
listItem.appendChild(listBtn);
listBtn.textContent = 'Delete';
list.appendChild(listItem);
listBtn.onclick = function(e) {
list.removeChild(listItem);
}
input.focus();
}
</script>
In my test above it works as it should but when I implement it in my form using the below the page reloads instead of adding a row.
html/pug
div#addMultipleDays.form-group.col-md-2
label(for='item') Enter a new
input.form-control(type='text' name='item' id='item')
button#addNew Add
ul#items
div.text-danger #{booking.addMultipleDaysError}
my js
$(document).ready(function() {
const list = document.querySelector('ul#items');
const input = document.querySelector('input#item');
const button = document.querySelector('button#addNew');
button.onclick = function() {
const myItem = input.value;
input.value = '';
const listItem = document.createElement('li');
const listText = document.createElement('span');
const listBtn = document.createElement('button');
listItem.appendChild(listText);
listText.textContent = myItem;
listItem.appendChild(listBtn);
listBtn.textContent = 'Delete';
list.appendChild(listItem);
listBtn.onclick = function(e) {
list.removeChild(listItem);
};
input.focus();
};
});
I have tried to add a listener (and plan to again once working) instead but this above is merely to get it working and test.
I can see the new item gets created but the page reloads when triggering the button.onclick
but I don't understand why. Why does the page reload? Am I missing anything obvious?