Question

I'm new with Javascript and I would really appreciate any help. I want to create a function that adds a row to my table and inserts an information to the cells that has been put into "input boxes".

function papildyti(){
        // Find a <table> element with id="myTable":
        var table = document.getElementById("myTable");

        var row = table.insertRow(-1);

        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        cell1.innerHTML = //information from input boxes goes here
        cell2.innerHTML = document.getElementById("input").innerHTML;//my try

    }
Was it helpful?

Solution

You can't use getElementById to get an input unless you give it an actual id attribute. You are trying to get the input by its tag name, so you should use getElementsByTagName instead..

cell1.innerHTML = document.getElementsByTagName('input')[0].value;

The [0] is because getElementsByTagName returns a node list and you want only the first item in the list (with index 0).

However, since its an input, its more conventional to give it a name attribute, so it could be submitted in a form, so you could instead do...

<input type="text" name="myInput">

and use the getElementsByName method, like...

cell1.innerHTML = document.getElementsByName('myInput')[0].value; 

I would recommend using jQuery instead though. It gives you many, many more options for selecting elements than just the native getElementBy* methods. Here are some examples of all the different ways you can get elements using jQuery selectors. Your example in jQuery could be as simple as...

cell1.innerHTML = $('input').val();

OTHER TIPS

var cell1 = document.getELementById('input1').value;
var cell2 = document.getELementById('input2').value;

var table = document.getElementById('myTable');

// your desired index where you want to place row

  var newrow = table.insertRow(1);
    //1st way 
    newrow.innerHTML = "<tr><td>"+cell1+"</td><td>"+cell2+"</td></tr>";

    // 2nd way
    var td1 = newrow.insertCell(0);
    td1.innerHTML = cell1;
    var td2 = newrow.insertCell(1);
    td2.innerHTML = cell2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top