Rnhep Rnhep - 3 years ago 150
Ajax Question

how to get value from Json in the click button

I'm working on a project. and can't seen to get this working. i make a call to my virtual localhost and get back product info from Json then place them in the buttons. i have a click function for the buttons and pass the item ID to my id. but some how it doesn't display item id. please take a look to see what went wrong. thanks.

function loadItem() {
var contentRows = $("#prod-diplay");
type: 'GET',
url: 'http://localhost:8080/items',
success: function (data, status) {
$.each(data, function (index, item) {
var ID = item.id;
var name = item.name;
var price = item.price;
var quantity = item.quantity;
var row = '<div class="col-sm-6 col-md-4">';
row += '<button type="button" class="btn btn-default" id="product"' + ID + '>';
row += '<p id="id">' + ID + '</p>';
row += '<p id="name">' + name + '</p>';
row += '<p id="price"> Price: ' + price + '</p>';
row += '<p id="quanity"> Quantity Left: ' + quantity + ' </p>';
row += '</button>';
row += '</div>'
$('#product' + ID ).click(function(){// get this working. left off from here when start back up.


error: function () {
class: 'list-group-item list-group-item-danger'
.text('Error calling web service. Please try again later.'));


<div class="row">
<div class="col-md-9" id="prod-diplay"></div>

<div class="form-group">
<label for="displayItem" class="col-sm-2 control-label">
<div class="col-md-8">
<input class="form-control" id="vending" placeholder="item no." required/>
<button type="button" id="purchase" class="btn btn-default">Make Purchase</button>

Answer Source

The problem is the way you are assigning the id to your button.

'<button type="button" class="btn btn-default" id="product"' + ID + '>'

If you inspect this button you will see

<button type="button" class="btn btn-default" id="product" 1="">..</button>

Check the id, it's id="product" and your ID from json is getting created as another attribute to the button.

To solve this you need to put quotes("") properly. Like this

'<button type="button" class="btn btn-default" id="product' + ID + '">'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download