Daniel Choi Daniel Choi - 7 months ago 8
HTML Question

onClick event doesn't work inside form tag

<!DOCTYPE html>
<html>
<head>
</head>
<script>
function removeP2() {
var parent = document.getElementById("section");
var child = document.getElementById("p2");
parent.removeChild(child);
}
</script>
<body>
<nav>
<form>
<button onclick="removeP2();">Remove</button>
</form>
</nav>
<section id="section">
<p id="p1">Paragraph One.</p>
<p id="p2">Paragraph Two.</p>
</section>
</body>
</html>


When I click the submit button, the function executes as usual, but after the function executes, the page reloads itself (removed P2 for a second).

I found a solution which is to delete the "Form" inside the "nav" tag, and it works fine. Just want to ask what is the problem cause that, and if I need to have the "Form" tag inside the "nav" tag, which part I need to fix?

Answer

Use the code below. It won't submit the form.

<button type="button">My Button</button>
Comments