0

I have a situation where I need to take data from few columns of a html table and display the data in separate rows.

.new td {border: 1px solid; padding: 2px;}
<div class="new"><table>
<tr>
<td>Name1,Name2,Name3,Name4</td><td>Age1,Age2,Age3,Age4</td><td>M,M,F,M</td>
</tr>
<tr>
<td>Name5,Name6,Name7</td><td>Age5,Age6,Age7</td><td>F,F,F</td></tr>
</table></div>

Now I want to separately change the data from each row to display separately in rows like below on the html page. Here the comma separated values can change in each row with new form submissions.

table td {border: 1px solid; padding: 2px;}
<p>For Row1</p>
<table>
<tr><td>Name1</td><td>Age1</td><td>M</td></tr>
<tr><td>Name2</td><td>Age2</td><td>M</td></tr>
<tr><td>Name3</td><td>Age3</td><td>F</td></tr>
<tr><td>Name4</td><td>Age4</td><td>M</td></tr>
</table>

<p>For Row2</p>
<table>
<tr><td>Name5</td><td>Age5</td><td>F</td></tr>
<tr><td>Name6</td><td>Age6</td><td>F</td></tr>
<tr><td>Name7</td><td>Age7</td><td>F</td></tr>
</table>

Can this be done with Javascript?

3

1 Answer 1

1

  function my_table_to_obj_arr(){
  	 var out=[];
  	 $('div.new table tr').each(function(){
  	 	 var names=$(this).find('td').eq(0).text();
  	 	   var names_arr=names.split(',');
  	 	 var ages=$(this).find('td').eq(1).text();
  	 	   var ages_arr=ages.split(',');
  	 	 var genders=$(this).find('td').eq(2).text();
  	 	   var genders_arr=genders.split(',');
  	 	 for(var key in names_arr){
  	 	 	out.push({'name':names_arr[key], 'age': ages_arr[key], 'gender': genders_arr[key]});
  	 	 }
  	 });
  	 return out;
  }


  function obj_arr_to_table(_obj){
  	 var table=$('<table/>');
  	 for(var key in _obj){
  	    var tr=$('<tr/>');
  	    var td_name=$('<td/>').text(_obj[key].name);
  	      tr.append(td_name);
  	    var td_age=$('<td/>').text(_obj[key].age);
  	      tr.append(td_age);
  	    var td_gender=$('<td/>').text(_obj[key].gender);
  	      tr.append(td_gender);
  	 	table.append(tr)
  	 }
  	 $('div.new').empty().append(table);
  }



  var my_obj=my_table_to_obj_arr();

  console.log(my_obj);

  obj_arr_to_table(my_obj);
       .new td {border: 1px solid; padding: 2px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="new">
 <table>
  <tr>
    <td>Name1,Name2,Name3,Name4</td><td>Age1,Age2,Age3,Age4</td><td>M,M,F,M</td>
  </tr>
  <tr>
    <td>Name5,Name6,Name7</td><td>Age5,Age6,Age7</td><td>F,F,F</td></tr>
  </table>
</div>

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.