I have a page that includes an x amount of items and each of these include a HTML 5 input.
When user changes the value of the input the server gets invoked via an AJAX call. The server then responds with JSON that includes an array of items that include a quantity value. If the returned quantity value is different from the one that was sent to the server (value of input) I need to change the input box value so that it is equal to the returned quantity value.
My problem is that I am getting an undefined in the alert instead of the id, could someone please tell me why, thank you in advance!
JAVASCRIPT:
//loop through JSON returned items array
for (var i = 0; i < data.items.length; i++) {
var id = data.items[i].id;
var title = data.items[i].title
var price = data.items[i].price
var quantity = data.items[i].quantity
var image = data.items[i].image
//output JSON to HTML
$("#result").append("<div class='column left'><img src="+ image + "width=100 height=100 style=padding:20px></div><div class='column middle' >" + " " + title + " " + price + "</div><div class='column right' ><input id='" + id + "' type=number min=1 max=10 step=1 value="+quantity+" maxlength=2 size=2 /> <br><a data-id='" + id + "' href=# id='remove'>Remove</a></div>");
//load subtotal when page loads
$('#subtotal').html(data.items_subtotal_price);
}
JSON
//QUANTITY update
$(":input").bind('keyup mouseup', function () {
$.ajax({
url: "https://example.com/cart/change.json",
dataType: "jsonp",
data: {
id: $(this).attr('id'),
quantity : $(this).val()
},
//JSON response
success: function(data) {
console.log(data); //formatted JSON data
$('#subtotal').html(data.items_subtotal_price); //set subtotal from JSON
//1. loop through JSON items for id >> get returned quantity value where id matches id of input box
//2. if quantity returned is not equal to the quantity sent then it's been disallowed by the server >> update input box value to equal returned value
// getting UNDEFINED -
alert($(this).attr('id'));
}
});
});