I have following HTML code, where I add items to cart and then finally click submit.
<div class="form-group">
<div>
<select id="available-options" multiple>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<button id="add-button" aria-label="Add">Add</button>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Update</button>
</div>
I have below Javascript
window.onload = function () {
const addButton = document.getElementById("add-button");
addButton.addEventListener("click", () => {
const selected = availableOptions.selectedOptions;
for (let i = 0; i < selected.length; i++) {
const option = selected[i];
selectedOptions.appendChild(option);
}
});
}
When I click add
button, both button events are getting fired!
2
Answers
The default
type
of button element is submit that causes the submission of the form. You can either specify the buttontype="button"
or prevent the default behavior usingevent.preventDefault()
.Demo:
Try to use
event.stopPropagation()
inside the event handler.This issue might be come because of the way of Javascript manage the events. Javascript by default follows the events bubbling. So here, when the target event is being completed, it will also called its next parent level event handler or better to say, event bubbling up to its parent and it will go till the final DOM event. So, to prevent this, we have to specifically mention
event.stopPropagation()
inside the handler method.I think above answer will help you. I’m also giving a reference link on this topic, please check this reference link.