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?
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);
});
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With