I need to increment some values contained in span tags and this is how I do it
This is the javascript part
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".incrementar", function(e)
{
var num = $(this).attr('data-value');
$elemento = "#" + $(this).attr('data-name');
$($elemento).html(++num);
});
</script>
And this is the html part
<?php for($i=0;$i<5;$i++): ?>
Número <span id="number<?=$i?>" class="numeros"><?=$i?></span>
<a href="#" class="incrementar" data-value="<?=$i?>" data-name="number<?=$i?>">Incrementar</a>
<br>
<?php endfor; ?>
Works correctly. It occurred to me to create the "id" attribute on the span element and the "data-value" and "data-name" attributes on the href element, to collect that data in javascript and then increment the value by one, but really this for loop is very small and in case the loop is bigger, which it will be, many data-value and data-name attributes will have to be created to collect those values
Could it be done differently without having to create the id attribute of the span and the data-value and data-name attributes of the href?
Thank you!
Yes, you can take the previous element, which would be him
span
and then increment its value