1

I have the following problem. I would like to add some data to a table using label values (in this case 7 & 5) but every time I try to add a value, the cells show the message "undefined". The main idea is to create a table which values are going to be used to draw a bar chart (graph) using the highcharts library

<h2>Add Row in JavaScript</h2>
<table id="table" cellspacing="0" border="1">
<tbody>
<tr>
<td>Name</td>
<td>Address</td>
</tr>
</tbody>
</table>
<button onclick="javascript:addRow('table')">Add row</button>
<br></br>
<label id="txt1" value="7" text="a">label 1</label>
<label id="txt2" value="5" text="b">label 2</label>

Script:

function addRow(id){

    var label = ($("#txt1").val());
    var label2 = ($("#txt2").val());

var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(label.value));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(label2.value));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}

Example in JFiddle Code

Highcharts library Code

3
  • 1
    var label = ($("#txt1").val()); is jQuery. Are you including / running jQuery? The rest is straight javascript (and if you're using jQuery, could be much simpler) Commented May 2, 2014 at 16:05
  • 1
    doing it in plain javascript is a pain, wouldn't you be missing the use of a higher level library such as knockout or angular? I like knockout because their tutorial makes it easy to learn: learn.knockoutjs.com/#/?tutorial=intro Commented May 2, 2014 at 16:10
  • A quick modification of your jsfiddle: http://jsfiddle.net/pHd8r/ Commented May 2, 2014 at 16:29

1 Answer 1

1

It seems you have taken label instead of textbox, anyway below is working code.

function addRow(id) {

    var label = ($("#txt1").attr("value"));
    var label2 = ($("#txt2").attr("value"));

    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var row = document.createElement("tr");
    var data1 = document.createElement("td");
    data1.appendChild(document.createTextNode(label));
    var data2 = document.createElement("td");
    data2.appendChild(document.createTextNode(label2));
    row.appendChild(data1);
    row.appendChild(data2);
    tbody.appendChild(row);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.