jacksonSD jacksonSD - 1 month ago 5
HTML Question

Change numberic value in td with jquery

How can I increase numeric values in a

<td>
element using jquery? I tried the following but no luck. I have a button with the id="#increaseNum", and am trying to change the td cell value with its click.

html:

<table>
<tr>
<td id="num">1</td>
<td id="num">5</td>
<td id="num">10</td>
</tr>
</table>


js:

$(document).ready(function() {
$("#increaseNum").click(function() {
$("#num").html(Number(("#num").innerText) + 1);
});
});


This only makes the first
<td>
value disappear. Any suggestions?

Answer

Try this :Remove duplicate ids and use class instead. iterate each num to increment its value as shown below

HTML:

<table>
<tr>
   <td class="num">1</td>
   <td class="num">5</td>
   <td class="num">10</td>
</tr>
</table>

jQuery :

$(document).ready(function () {
    $("#increaseNum").click(function () {
        $(".num").each(function(){
           $(this).html(parseInt($(this).html())+1);
        });
    });
});