0
I have this code that generates a list of items in input form:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "
<tr>
<tr>
<td><input type='number'
name='idrequisicao'
min='0'
max='999999'
readonly='readonly'
value=". $row["idsolicitacao"] .">
</td>
<td><input type='text'
name='descmaterial'
readonly='readonly'
value=". $row["descmaterial"] .">
</td>
<td><input type='number'
name='quantidade'
id='quantidade$n'
min='0'
max='9999999'
readonly='readonly'
value=". $row["quantidade"] .">
</td>
<td><input type='number'
name='valunit'
id='valunit$n'
min='0'
max='9999999999'>
</td>
<td><input type='number'
name='total'
id='total$n'
min='0'
max='999999'
readonly='readonly'
value=". $row["total"] .">
</td>
</tr>
";
$n += 1;
It does what I need, but my problem is in jQuery, so the user insert the value into the input valunit(unit value) it multiplies by the amount bringing the total value into the total value input, but the code I’ve been able to do so far is static and I couldn’t think of anything to make it dynamic:
$(document).ready(function(){
$('#valunit0').on('keyup', function() {
var vunit = parseFloat($('#valunit0').val() != '' ? $('#valunit0').val() : 0);
var qtd = parseFloat($('#quantidade0').val() != '' ? $('#quantidade0').val() : 0);
$('#total0').val(vunit*qtd);
})
$(document).ready(function(){
$('#valunit1').on('keyup', function() {
var vunit = parseFloat($('#valunit1').val() != '' ? $('#valunit1').val() : 0);
var qtd = parseFloat($('#quantidade1').val() != '' ? $('#quantidade1').val() : 0);
$('#total1').val(vunit*qtd);
})
$(document).ready(function(){
$('#valunit2').on('keyup', function() {
var vunit = parseFloat($('#valunit2').val() != '' ? $('#valunit2').val() : 0);
var qtd = parseFloat($('#quantidade2').val() != '' ? $('#quantidade2').val() : 0);
$('#total2').val(vunit*qtd);
})
Is there any way to make this code dynamic so that it is not necessary to modify jQuery for each item that is presented? I accept suggestions in other languages if necessary. Thank you!
What have you tried?
– Julyano Felipe
I tried to generate without the variable $n in php, but in this way only the first input performed the calculation.
– Leonardo Hernandez