Lini Lini - 1 month ago 5
Javascript Question

How to get odd/even value from array and display in table using Javascript

I have

dataArr = ["1","Maths","2","Science"];
I need to display the values 1,2(S.No) in the first column and the (Subject name) Maths,Science in the second column of a dynamic table.

Any way to do this using jquery/javascript?

Sample table code:

$("#subjectTable").append("<table style='width:100%; height: 4em; border-spacing: 0px;'><tr><td style='width:25%'>"+OddpositionVal+"</td><td style='width:25%'>"+EvenpositionVal+"</td></tr></table>");

Answer
var dataArr = ["1","Maths","2","Science"];

Add a bare bones table to a div.

$("#subjectTable").append('<table id="table"></table>');

For each table row loop over the array in steps of 2 (i+=2). oddPositionVal is the first element in the step, evenPositionVal is the second element.

Build the row HTML and then append it to the table.

for (var i = 0, l = dataArr.length; i < l; i+=2) {
  var oddPositionVal = dataArr[i];
  var evenPositionVal = dataArr[i + 1];
  var rowhtml = '<tr><td style="width:25%">' + oddPositionVal + '</td><td style="width:25%">' + evenPositionVal + '</td></tr>';
  $('#table').append(rowhtml);
}

DEMO