Jerry
Jerry

Reputation: 123

Why does my attempt to add a new row to my table (made w/o a table element) keep showing up and disappearing?

I'm trying to make a table in Javascript that does not use a table element, and I'm using pure vanilla nodeJS. I can get a new row to show up very briefly, but it disappears when I hit the button that made it show up in the first place. My code is:

<!DOCTYPE html>
<html>
<body>

<h1> Title Tests </h1>

<div id="Experiments">
    <form id="Exp">
        <input type="text" name="url box" placeholder="publisher URL"><br>

                <div class="Title">
                    <input type="text" name="title box" placeholder="Test Title"><br>
                </div>
                <button id="addButton" onclick="newRow()">+</button><br>

        <input type=submit value="Submit">
    </form>
</div>

<script>
    function newRow(){
        var number = 2;

        var newTitleRow = document.createElement('div');
        newTitleRow.setAttribute('id',`Title${number}`);

        var newBT = document.createElement('input');
        newBT.setAttribute('type','text');
        newBT.setAttribute('name',`title box ${number}`);
        newBT.setAttribute('placeholder','Test Title');

        newTitleRow.appendChild(newBT)

        var button = document.querySelector("#addButton");
        button.before(newTitleRow);

        number++;
    }
</script>   

</body>
</html>

Upvotes: 0

Views: 26

Answers (1)

obscure
obscure

Reputation: 12891

The problem is that you're using a html <button> inside a <form> element. This means it will automatically act as a submit button unless you declare it to be something different. So as soon as you push the + button it will try to submit the form to an undefined URL.

To work around you need to define that + button to be of type "button" like:

<button type="button" id="addButton" onclick="newRow()">+</button><br>

Upvotes: 2

Related Questions