I have been struggling with the use of Javascript on my site for a number of days.
All I wanted is simple – just a button within a <form> and once the button “Add” is clicked, a small Javascript is executed to update content of <div> by updating innerHTML.
However whenever “Add” is clicked, the form is submitted as well, I finally found out the solution by adding e.preventDefault() in, below are example key codes:
//add listener
document.getElementById(‘add’).addEventListener(‘click’, add);
function add(e) {
…
// prevent form submission (return false deson’t work)
e.preventDefault();
}
I’m still not clear as to why the “Add” button functioned as “submit” in the form, but preventDefault() works!
Use of Javascript on form submit