Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change numeric 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?

like image 945
jacksonSD Avatar asked Dec 30 '25 13:12

jacksonSD


2 Answers

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);
        });
    });
});
like image 129
Bhushan Kawadkar Avatar answered Jan 01 '26 02:01

Bhushan Kawadkar


Try substituting class=num for id=num to replace duplicate id's with same className ; adding <tbody> element to parent <table> element

$("#increaseNum").on("click", function() {
  $(".num").map(function(i, el) {
    el.innerHTML = 1 + Number(el.innerHTML);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button id="increaseNum">click</button>
<table>
  <tbody>
<tr>
   <td class="num">1</td>
   <td class="num">5</td>
   <td class="num">10</td>
</tr>
    </tbody>
</table>
like image 22
guest271314 Avatar answered Jan 01 '26 02:01

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!