So I am using a foreach loop (php) and in that loop a jQuery for-loop
here is my code
foreach($products as $product):
?>
var qty = $('#product_<?= $product->id ?>').val();
var i;
for (i = 0; i < qty; ++i) {
//remove Item from list
// alert(i);
$('#delete_[<?=$product->id?>]['+ i +']').click(function(){
swal({
title: "<?= __('Do you really want to delete order No. {0}?', [$product->id]); ?>",
type: "warning",
}, function(isConfirm){
if (isConfirm) {
alert('delete me');
}
else {
swal("<?= __('The order is canceled') ?>", " ", "error");
}
});
});
$(wrapper).append(
...
'<div class="actions corner">' +
'<a id="delete_[<?=$product->id?>]['+ i +']" title="<?= __("Cancel order") ?>" class="user-action-button-delete">' +
'<i class="zmdi zmdi-delete"></i>' +
'</a>'+
'</div>'+
...
);
}
<?php
endforeach;
?>
The loop is working but for some reason I don't get the value of the second dimension for div #delete_[1]['+i'] in //remove Item from list
Under this code in "wrapper" element is same process/logic and I am getting value of "i"
Why does the browser parse i like i and not like counter?
thx
There is pretty same code with same error
//Start delete block
<?php
foreach($products as $product):
?>
ar qty = parseFloat($('#product_<?= $product->id ?>').val());
var i = 0;
for (i = 0; i < qty; ++i) {
//Start remove Item from list
var delete_div = $('#delete-<?=$product->id?>-'+ i);
var delete_element = $('#preselected-<?=$product->id?>-'+ i);
delete_div.on('click', function(){
swal({
title: "<?= __('Do you really want to delete product No. {0}?', [$product->name]); ?>",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "<?= __('OK'); ?>",
cancelButtonText: "<?= __('Cancel'); ?>",
closeOnConfirm: true,
closeOnCancel: true
}, function(isConfirm){
console.log(i);
});
});
}
<?php
endforeach;
?>
Currently qty
is getting the value from your input and you are using that to create the upper limit of your loop.This is assuming that is an input or other element that has a value attribute. If its not - you will need to use .text() or .html().
But even if its an input - qty
will be a string - even a number input returns a string value from .val() so you need to parse the value into a number to be able to use as the iterating count. So i
is not the problem - it is simplynot incrementing because qty
is not a number.
var qty = parseInt($('#product_<?= $product->id ?>').val());
or
var qty = parseFloat($('#product_<?= $product->id ?>').val());
then qty will be a number that you can use in your for loop:
for (i = 0; i < qty; ++i) {...