Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery how to add index number dynamically to a table
    text
    copied!<p>I have created a table and I can add and remove rows using jQuery when a checkbox is checked. My question here is, how can I add an index number at the first column dynamically?</p> <p>My table:</p> <pre><code> &lt;div&gt; &lt;table class="config" id="status_table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th colspan="4"; style= "padding-bottom: 20px; color:#6666FF; text-align:left; font-size: 1.5em"&gt;Output Status&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Index&lt;/th&gt; &lt;th&gt;Output Type&lt;/th&gt; &lt;th&gt;Output Number&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td &gt;1&lt;/td&gt; &lt;td &gt;&lt;p id="type_row_one"&gt;&lt;/p&gt;&lt;/td&gt; &lt;td &gt;&lt;p id="number_row_one"&gt;&lt;/p&gt;&lt;/td&gt; &lt;td&gt; &lt;img class="image" id = "off" style="margin-left:20px" src="static/OffLamp-icon.png" &gt; &lt;img class="image" id = "on" style="margin-left:20px" src="static/OnLamp-icon.png" &gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>My jQuery:</p> <pre><code>$('#outputCB').change(function(){ if($('#outputCB_1').is(':checked')){ $('#status_table tr:last').after('&lt;tr id="output_newrow_1"&gt;&lt;td&gt;index+1&lt;/td&gt;&lt;td&gt;testing&lt;/td&gt;&lt;/tr&gt;');} else{ $('#status_table').find("#output_newrow_1").remove(); } }); </code></pre> <p>So instead of <code>"index+1"</code> I want it to be able to increment from the previous index number, and decrease if the row is removed. How should I go about doing it? Can I assign a variable and ++1 or --1 at the Javascript? I don't really know where to start....</p> <p>UPDATE:<br> I tried this but failed:</p> <pre><code> var index=1; $('#outputCB').change(function(){ if($('#outputCB_1' ||'#outputCB_2').is(':checked')){ index++; $('#status_table tr:last').after('&lt;tr id="output_newrow_'+index+'"&gt;&lt;td&gt;'+index+'&lt;/td&gt;&lt;td id="type_row_'+index+'"&gt;type_row_'+index+'&lt;/td&gt;&lt;td id="num_row_'+index+'"&gt;num row '+index+'&lt;/td&gt;&lt;td&gt;&lt;img class="image" src="static/OffLamp-icon.png" style="height:64px; width=64px"/&gt;&lt;/td&gt;&lt;/tr&gt;'); } else{ index--; $('#status_table').find("#output_newrow_'+index+'").remove(); } }); </code></pre> <p>it will never remove anything and it added 2 rows at a time when #outputCB_1 is checked again. :/ Why so? (sorry this is too long for a comment.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload