How to add object that is created with a button to a table?

Viewed 126

I am trying to use a form to create an object using JS and then take those object properties and add them to a table on the page. Here is what I have come up with, but I don't understand why it is behaving the way that it is. It flashes like it wants to add something but no more.

HTML

<form>
    <fieldset>
        <legend>Enter the item name.</legend>
        <input type="text" id="name" /> </fieldset>
    <fieldset>
        <legend>Enter the quantity of units needed.</legend>
        <input type="number" id="amount" /> </fieldset>
    <fieldset>
        <legend>Enter the name of the store to buy this from.</legend>
        <input type="text" id="store" /> </fieldset>
    <button onclick="add()">Add Item</button>
</form>

JavaScript

//global variable
var myItem;

//custom object constructor
function Item(name, amount, store) {
    this.itemName = name;
    this.itemAmount = amount;
    this.itemStore = store
}

function add() {
    var itemName = document.getElementById("name").value;
    var itemAmount = document.getElementById("amount").value;
    var itemStore = document.getElementById("store").value;
    //creates a new item object and stores it
    myItem = new Item(itemName, itemAmount, itemStore);

    // Find a <table> element with id="list":
    var table = document.getElementById("list");

    // Create an empty <tr> element and add it to the 1st position of the table:
    var row = table.insertRow(0);

    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);

    // Add some text to the new cells:
    cell1.innerHTML = "y";
    cell2.innerHTML = "y";
    cell3.innerHTML = "y";


}
1 Answers

Always define button type attribute, different browser reacts differently to button without attribute i.e firefox it acts like "submit" so in your case it flashed (reloaded) https://www.w3schools.com/tags/att_button_type.asp so to your button line add type="button"

<button type="button" onclick="add()">Add Item</button>
Related