Joanna Joanna - 1 month ago 10
Javascript Question

Dynamically adding tags in HTML document on button click immediately reversed

I have very simple table with 3 columns that show 2 teams and their scores. Below the table there is a form that enables adding new teams and their scores to the table. The new row should be added only when given teams have different names and scores aren't negative. I wrote the below code in JavaScript but it doesn't add the row - it is just showing new row only when confirm button is clicked. When it's not, the data dissapear. Can you look at my code and check what may be wrong with it? I tried to add rows to the table without validate event and it worked perfectly fine.

document.addEventListener("DOMContentLoaded", function () {

var team1 = document.getElementById("team1");
var team2 = document.getElementById("team2");
var points1 = document.getElementById("points1");
var points2 = document.getElementById("points2");
var button = document.querySelector(".btn-primary");
var table = document.querySelector("table");

function validate(e) {
if (team1.value === team2.value) {
alert("Enter two differnt teams' names");
} else if (points1.value < 0 || points2.value < 0) {
alert("Points number cannot be negative");
} else {
var newRow = document.createElement("tr");
table.appendChild(newRow);
var newTeam1 = document.createElement("td");
newRow.appendChild(newTeam1);
newTeam1.innerHTML = team1.value;
var newTeam2 = document.createElement("td");
newRow.appendChild(newTeam2);
newTeam2.innerHTML = team2.value;
var newPoints = document.createElement("td");
newRow.appendChild(newPoints);
newPoints.innerHTML = points1.value + " - " + points2.value;
}
}

button.addEventListener("click", validate);
});

Answer

The problem here is that the button is part of a HTML <form>. Clicking the button submits the form and leads to the page being reloaded.

There are three different possible solutions to the problem. use either of those:


1) Place the button outside the form. Remove the <form></form> tags if you don't need them or place the button somewhere outside the <form></form> tags.


2) Specifically mark the button as being a button that does not submit the form:

<button type="button" class="btn-primary">Push me</button>

The type="button" prevents the button from submitting the form.


3) In the javascript handler of the button tell the button to not show its default behaviour like this:

function validate(e) {
{
    // Your current code here       

    // Additional code to prevent button from showing default behaviour
    e.preventDefault();
    e.returnValue = false;
}

The e.returnValue = false; is for older browsers, the e.preventDefault(); is for newer browsers.

Comments