So here is my code,
function getProduct(){
$.ajax({
url:"./services/getproductlist.php",
method: "GET",
success: function(res){
$("#product-list").html('');
var count = 1;
console.log(res);
res.forEach(function(item){
var row = $("<tr></tr>");
var col1 = $("<td>" count "</td>");
var col2 = $("<td>" item['nama_produk'] "</td>");
var col3 = $("<td>" item['harga_produk'] "</td>");
var col4 = $("<td><input type='number' name='inp' id='inpqty' required value = '<?php echo 2 ?>'></input></td>");
var btn = $('<td scope="col"></td>');
var add = $('<a href="#" id="add-btn"><svg class="bi me-2" width="16" height="16" style="color: black; margin-left: 10px;"><use xlink:href="#basket"/></svg></a>');
var add2 = $('<a href="#" id="inp-btn"><svg class="bi me-2" width="16" height="16" style="color: black; margin-left: 10px;"><use xlink:href="#basket"/></svg></a>');
add.data('id_produk', item['id_produk']);
add2.data('qty', $("#inpqty").val());
console.log(item['id_produk']);
console.log(item['harga_produk'] * $("#inpqty").val());
col1.appendTo(row);
col2.appendTo(row);
col3.appendTo(row);
col4.appendTo(row);
add.appendTo(btn);
add2.appendTo(btn);
btn.appendTo(row);
count ;
$("#product-list").append(row);
});
$("#tableImage").DataTable();
},
error: function(){
alert('fail');
}
});
}
When I tried console.log($("#inpqty").val())
, the first value always return undefined
but not the others.
I tried to find the problem but I can't, is there anyone that can help me?
CodePudding user response:
Inside the for loop:
res.forEach(function(item){
var row = $("<tr></tr>");
var col1 = $("<td>" count "</td>");
var col2 = $("<td>" item['nama_produk'] "</td>");
var col3 = $("<td>" item['harga_produk'] "</td>");
var col4 = $("<td><input type='number' name='inp' id='inpqty' required value = '<?php echo 2 ?>'></input></td>");
...
add2.data('qty', $("#inpqty").val());
console.log(item['id_produk']);
console.log(item['harga_produk'] * $("#inpqty").val());
...
$("#product-list").append(row);
});
The first time you look for inpqty
, the element has not been added to the page body, product-list
, yet.
That's why it return NaN
I'm not sure the value is static or not, but with the info. you provided, you can do this:
console.log(item['harga_produk'] * <?php echo 2 ?>);
CodePudding user response:
You multiplying item['harga_product']
with the element doesnt exist in the element.
You see the first time it loop, there’s no inpqty
inserted to document yet, hence no value and undefined, the solution I think you can try console them below $("#product-list").append(row);
OR
when you multiply
const qtyValue = isNaN(parseInt($("#inputqty").val())) ? 0 : $("#inputqty").val()
Here I use 0 when element is not defined as the default value. The when you multiply
item['harga_produk'] * qtyValue