schinken82
schinken82

Reputation: 43

Add inputs from modal to a new table row using javascript

I have a modal with 2 input fields, and a table with two columns. I'm trying write a function that adds a new row to the table when a button is clicked. However when I test my code nothing happens.

The input fields have the id's "modal_type" and "modal_price", the table has the id "acc_table1"

JS:

{
         var new_acc=document.getElementById("modal_type").value;
         var new_bal=document.getElementById("modal_price").value;

         var table=document.getElementsById("acc_table1");
         var table_len=(table.rows.length)-1;
         var row = table.insertRow(table_len).outerHTML="<tr id='acc_row"+table_len+"'><td id='acc_name"+table_len+"'>"+new_acc+"</td><td id='acc_balance"+table_len+"'>"+new_bal+"</td></tr>";

         document.getElementById("modal_type").value="";
         document.getElementById("modal_price").value="";
       }

I'd appreciate any suggestions on what I could change!

Upvotes: 0

Views: 129

Answers (1)

Christian
Christian

Reputation: 7852

Try this:

const newRow = table.insertRow(-1);                // appends a new row 
newRow.itemId = 'acc_row';                         // set item id to the new row 
const accCell = newRow.insertCell(0);              // add a cell to the new row at index 0
accCell.itemId = 'acc_name';                       // set item id to the cell
const accText = document.createTextNode(new_acc);  // create a text node for new_acc
accCell.appendChild(accText);                      // set text node to acc cell
const balCell = newRow.insertCell(1);              // add a cell to the new row at index 1
balCell.itemId = 'acc_balance';                    // set item id to the cell
const balText = document.createTextNode(new_bal);  // create a text node for new_bal 
balCell.appendChild(balText);                      // set text node to bal cell

Upvotes: 1

Related Questions