How to overwrite the values of the first column in every rows in a HTML tbody table with JavaScript and with jQuery? -


here table example:

<table id="tableid">  <thead>   <tr>    <th>line number</th>    <th>value</th>   </tr>  </thead>  <tbody>   <tr>    <td>2</td>    <td>value 1</td>   </tr>   <tr>    <td>3</td>    <td>value 2</td>   </tr>   <tr>    <td>1</td>    <td>value 3</td>   </tr>  </tbody> </table> <input type="button" value="relineing" onclick="relinenumbering('tableid')"/> 

i want "line number"s in sequence this:

<table id="tableid">  <thead>   <tr>    <th>line number</th>    <th>value</th>   </tr>  </thead>  <tbody>   <tr>    <td>1</td>    <td>value 1</td>   </tr>   <tr>    <td>2</td>    <td>value 2</td>   </tr>   <tr>    <td>3</td>    <td>value 3</td>   </tr>  </tbody> </table> <input type="button" value="relineing" onclick="relinenumbering('tableid')"/> 

i've tried both of snippets below:

function relinenumbering(tableid) {   $('#'+tableid+' tbody').each(function (i) {     this.rows[i].cells[0].text('i');   }); }  function relinenumbering(tableid) {   var rowcount = $('#'+tableid+' tbody tr').length;   (var i=0; i<rowcount; i++) {     $('#'+tableid+' tbody').rows[i].cells[0].text(i);   } } 

could me?

this change first column sequential number starting 1:

function relinenumbering(tableid){     $('#' + tableid + ' > tbody > tr').each(function(i, val){         $('td:first', this).text(i+1);      }); } 

fiddle

plain javascript - fiddle:

function relinenumbering(tableid){     var table = document.getelementbyid(tableid);     var total = table.rows.length;     for(var i=0; i<total; i++){         if(i > 0){             table.rows[i].cells[0].innerhtml = i;         }     } } 

or creating text node instead of setting innerhtml. in simple scenario use of innerhtml isn't problem, want work dom elements , set text node instead of setting html:

function relinenumbering(tableid){     var table = document.getelementbyid(tableid);     var total = table.rows.length, text, cell;     for(var i=0; i<total; i++){         if(i > 0){             text = document.createtextnode(i);             cell = table.rows[i].cells[0];             cell.removechild(cell.firstchild);             cell.appendchild(text);         }     } } 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -