Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Selecting item in list and displaying the selected item's information in another div

I am getting JSON data (businesses) from the yelp API. I loop through the data to display the businesses, and want to display more information about the business when clicked on in another div. So far I have:

        function display_results(businesses) {
            var options = '';
            for (var i = 0; i < businesses.length; i++) {
                options += '<div class="optbtn" value="' + i + '">' + businesses[i].rating.toFixed(1) + "/5\u2606  " + businesses[i].name + '</div>';
            }
            $('#businesses').html(options);


            $('.optbtn').click(function () {
                // index problems
                var index = $(this).val();
                console.log("index: " + index);
                var details = businesses[index];

                var info = '';
                for (key in details) {
                    info += key + ': ' + details[key] + '<br>';
                }
                $('#info').html(info);
            });
        }

        $(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);
                        }
                    });
                }
            });
        });
    <div class="ui-widget">
        <label for="search_bar">Business Search: </label>
        <input id="search_bar" style="width: 400px;">
    </div>

    <div class="ui-widget">
        Businesses:
        <div id="businesses" style="height: 400px; width: 600px; overflow: auto; white-space: pre;"
            class="ui-widget-content" />
    </div>

    <div class="ui-widget">
        Info:
        <div id="info" style="height: 400px; width: 600px; overflow: auto; white-space: pre;"
            class="ui-widget-content" />
    </div>

My plan was to set an index value for each div containing a business and then upon click use that value to get the rest of the information to display. My problem is that I seem to not be able to actually get the index value using var index = $(this).val();. I am new to all of this and would love some guidance on where I went wrong!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The main issue in your code is because valid HTML div elements should not have a value attribute to be read through jQuery's val() method. The easy fix for this would be to use data attribute to store the index or id of the related array entity within the HTML.

Also note that there's some other optimisations you can make to the logic to improve it:

  • Use Array.map() and string interpolation to build the HTML more succinctly
  • Use a single delegated event handler for all dynamic content
  • Use Object.entries() to retrieve an array-like object containing the key/value pairs within a given object.
  • Put CSS rules in an external CSS stylesheet, not inline in HTML

With that said, this should work for you:

jQuery($ => {
  let $businesses = $('#businesses');
  
  // handle click on the business rating
  $businesses.on('click', '.optbtn', e => {
    let index = $(e.currentTarget).data('index');
    let business = $businesses.data('response')[index];    
    $('#info').html(Object.entries(business).map(([k, v]) => `<p>${k}: ${v}</p>`)); 
  });
  
  // update the DOM based on the AJAX response:
  let display_results = businesses => $businesses.html(businesses.map((b, i) => `<div class="optbtn" data-index="${i}">${b.rating.toFixed(1)}/5\u2606 ${b.name}</div>`))
  
  // make your Autocomplete/AJAX call here. 
  // mock AJAX response handler:
  let ajaxResponse = [{ rating: 1.11, name: 'Foo', address: '123 Any Street' },{ rating: 2.22, name: 'Bar', address: '456 Any Town' },{ rating: 4.44, name: 'Fizz', address: '789 Any City' },{ rating: 5.00, name: 'Buzz', address: '123 Any Avenue' }];

  display_results(ajaxResponse); // build the UI from the dataset
  $businesses.data('response', ajaxResponse); // store the response for later use
});
#search_bar { 
  width: 400px;
} 

.ui-widget-content {
  width: 600px;
  overflow: auto;
  margin-bottom: 10px;
}

.ui-widget-content p {
  margin: 0 0 5px;
}
<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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!