I am getting JSON data (businesses) from the yelp API. I loop through the data to display the businesses, and upon clicking on a certain business, display more information about it. I also want to include a button that will add the business and its location information to a list to use later on. This is what I have so far:
function display_results(businesses) {
var options = '';
for (var i = 0; i < businesses.length; i++) {
options += '<div class="optbtn" data-value="' + i + '">' + businesses[i].rating.toFixed(1) + "/5u2606 " + businesses[i].name + '</div>';
}
$('#businesses').html(options);
// display details on click
$('.optbtn').click(function () {
var index = $(this).data('value');
console.log("index: " + index);
var details = businesses[index];
console.log(businesses[index].name);
var info = '';
info += 'Name: ' + details.name + '<br>';
info += 'Rating: ' + details.rating + '<br>';
info += 'Price: ' + details.price + '<br>';
info += 'Hours: ' + details.hours + '<br>';
info += 'Location: ' + details.location.address1 + ', '
+ details.location.city + ', '
+ details.location.state + ' '
+ details.location.zip_code + '<br>';
info += '<br>';
info += '<button type="button" class="add btn btn-primary" data-value="' + index + '">' + 'Add to List' + '</button>';
$('#info').html(info);
});
$(document).on('click', 'btn', function () {
console.log("button clicked");
var d = $(this).data('value');
console.log("btn: " + d);
});
}
$(function () {
$("#search_bar").autocomplete({
source: "/autocomplete",
minLength: 3,
select: function (event, ui) {
$.ajax({
url: "/business_search",
type: "GET",
data: {
term: ui.item.value
},
success: function (result) {
display_results(JSON.parse(result).businesses);
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="ui-widget">
<label for="search_bar">Business Search:</label>
<input id="search_bar" />
</div>
<div class="ui-widget">
Businesses:
<div id="businesses" class="ui-widget-content"></div>
</div>
<div class="ui-widget">
Info:
<div id="info" class="ui-widget-content"></div>
</div>
I am having trouble getting the button to actually work. Additionally, what would be the best way to store the business if I wanted to hold the name, location, and other related information?