Utilizing Jquery Autocomplete with multiple arrays for data sourcing

I am facing a challenge where I want to display both doctors and their connections in an autocomplete search using jQuery. Although I have successfully displayed the doctors, I'm struggling to categorize and display data from both arrays separately under doctor and connection headings. The JSON returned from the server is structured like this:

    {"connections":
    [{"ConnectionID":"8","ConnectionName":"Saima Fayyaz","ImageName":"201304061217391.5x1.5.jpg"}],
    "doctors":
[{"DoctorID":"4","DoctorName":"Imran Saeed Ali","ImageName":"20130516210722ImranSAli.jpg","Type":"Doctor"},
{"DoctorID":"8","DoctorName":"Saima Fayyaz","ImageName":"201304061217391.5x1.5.jpg","Type":"Doctor"},
{"DoctorID":"10","DoctorName":"Sabira  Javaid","ImageName":"20130406123414123.jpg","Type":"Doctor"}]}

My JavaScript code snippet for the autocomplete functionality is as follows:

<script type= "text/javascript">
$(document).ready(function () {

    $("#people").autocomplete({
        minLength: 0,
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("Search","SearchPathologist")',
                dataType: "json",
                data: {
                    term: request.term,
                    flag: "all"
                },
                success: function (data) {
                    //alert(data.doctors);
                    response($.map(data.doctors, function (item) {
                        // alert(item.Type);
                        return {
                            //data: item.doctors
                              id: item.DoctorID,
                              name: item.DoctorName,
                              photo: item.ImageName,

                        }
                    }));

                }
            });
        },
        focus: function (event, ui) {

        }

    })
.data("autocomplete")._renderItem = function (ul, item) {

    return $("<li></li>")
    .data("item.autocomplete", item)
    .append("<div style='width:100%; margin:auto; background:white; min-height:20px;'><div style='border-bottom:1px dashed gray;'><div style='float:left;  width:16%; min-height:35px; margin:auto;'><img src='http://olivecliq.com:84/carepoint/doctor_images/"+item.photo+"' width='31px' style='margin-top:4px; margin-left:1px;' /></div><div class='mid_card'><h2> " + item.name + "</h2><h3>Use StrongVPN &amp; have a USA or UK IP address anywhere.</h3></div><div style='float:left;width:10%; min-height:25px; margin:auto;'> <img src='@Url.Content("~/images/arrow.png")' width='25' style='margin-top: 10px;' /></div><div style='clear:both;'></div></div>")
    .appendTo(ul);


});

Any assistance on how to handle this situation would be highly appreciated.

Answer №1

To overcome the issue, I implemented a similar solution.

Below is the jQuery code utilized:

<script type="text/javascript">
$(document).ready(function () {
    var drew = false;
    $("#people").on("keyup", function (event) 
    {
        var query = $("#people").val();

        if ($("#people").val().length >= 1) 
        {
            $('div#loaderContainer').show();
            $.ajax({
                url: '@Url.Action("Search","SearchPathologist")',
                dataType: "json",
                data:
                    {
                        term: query,
                        flag: "all"
                    },
                    error: function()
                    {
                    $.fallr('show', {
        content: '<p>An error occurred! Your session may have expired.</p>'
                    });
                    },
                success: function (data) 
                {
                    $('div#loaderContainer').hide();

                        if (drew == false) 
                        {
                            $("#people").after("<ul id='res' class='ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all' role='listbox' aria-activedescendant='ui-active-menuitem' style='z-index: 10005; display: block; width: 293px;'></ul>");
        
                            drew = true;

                            $("#res").on("click", "li.item", function () 
                            {
                                $("#people").val($(this).text());
                                $("#res").empty();
                            });
                        }
                        
                        else 
                        {
                            $("#res").empty();
                        }

                        $.each(data.doctors, function (i, item) {
                            // Code omitted for brevity
                        });

                        $.each(data.connections, function (i, item) {
                            // Code omitted for brevity
                        });

                    if($('button#searchDDL').html() == "Doctors")
                    {
                    $('div#connections').hide();
                    }
                    if($('button#searchDDL').html() == "Connections")
                   {
                   $('div#doctors').hide();
                   }

                }


            });
        }

        else
        {
        $("#res").empty();
        $( "#res" ).remove();
        drew = false;
        }
    });

    $("input#people").focusout(function () {

$( "#res" ).remove();
drew = false;
});
});

</script>

The HTML used is as follows:

 <div class="search_input"><input type="text" id="people" placeholder="Search for specialist doctors and more.." />
</div>
<button type="submit" class="search-button" value="Search" name="search">
        <span><img src="@Url.Content("~/images/search-icon.png")" height="20" /></span>
      </button>
</div>

Moreover, the action taken is described below:

public JsonResult Search(string term, string flag)
{
// Code implementation here
}

WCF Service method utilized:

public SearchResult Search(string PersonID,string term,string flag)
{
// Code implementation here
}

Defined classes like SearchResult, Doctor, and Connection:

// Class definitions

Tutorial post on this implementation available at:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for retrieving JSON-formatted data from an API in Python and saving it to a .db file

I need assistance with fetching data from an API in JSON format at this URL using Python. I aim to create a table filled with the retrieved data and then perform SQL queries on it using sqlite3 by pushing the data to my database named pitch.db. Below is t ...

Animate the smooth transition of a CSS element when it is displayed as a block using JQuery for a

I have implemented the collapsible sections code from W3 School successfully on my website. Now, I am trying to achieve a specific functionality where the "Open Section 1 Button" should slide down with a margin-top of 10px only if the first section "Open S ...

Encountering a "SyntaxError: Unexpected token '/' in... index.ejs while compiling ejs" issue following the recent npm package updates

After upgrading EJS from version 2.7.4 to 3.1.5 along with some other packages in my project, I am encountering a problem where I can no longer access any of the webpages. Instead, an error is being thrown on every page. Additionally, after the update, I s ...

The "click" event is only effective for a single use

I am looking for a way to trigger the click event more than once in my project. I attempted using "live" but it didn't work as expected. There are 2 other similar scripts in this Django project. If you have any suggestions on improving this project, p ...

How can the dot badge in Material-UI be enlarged?

I'm in need of a badge component that serves as an indicator without displaying any values. I opted for the dot variant, but it's too small for my liking. I tried modifying it with CSS, but it doesn't seem to be working as expected. Any sugg ...

Automatically populating username and password fields

Is it possible to set up automatic username and password filling on my website for users who have saved their login information in their browser? I want the user to just hit enter to login. Some websites already have this feature enabled, but others requi ...

Optimal placement and size for the slick slider

I am new to CSS and currently experimenting with the Slick slider on a project: My setup involves a div container that spans 100% of the width of the page. Inside this container, there is another div (housing the slider) that takes up 80% of the width. D ...

PHP isn't getting the AJAX POST data from the JavaScript file

I've been stuck on this issue for hours now, unable to find a solution. Here is the javascript code snippet: function sendMovement(cel) { var name = "test"; $.ajax({ type: 'POST', url: '../game.php', ...

How can you refresh the information shown in a separate component from the search input with a live search bar?

Currently, I am working on integrating a live search functionality into my Next.js application. While I have successfully managed to capture input changes, I am facing difficulties in filtering the results based on the user input. Here is a snippet of the ...

Rails issue: Active Model Serializer searching for incorrect serializer

Every time I try to use the create method, it throws a NameError at me. Failure/Error: post :create, { user: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a7aca5b6a8a1b784a1bca5a9b4a8a1eaa7aba9">[email ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

Incorporate Aria Label into a Website Link

Currently working on enhancing website accessibility. I have identified a close menu button that lacks an Aria Label, and my goal is to rectify this using JavaScript. Although I am utilizing the script below to target the specific ID and add the attribute ...

I am currently in the process of verifying email addresses

I attempted to validate multiple email addresses from a txt file and then save the valid emails to another txt file using nodejs. Unfortunately, it did not work as expected. Despite successfully reading the file, all emails were deemed invalid, even though ...

Tips for incorporating in/out animations with a container for the Slide feature:

I need help creating a component that will slide to the right when mounted, and to the left when unmounted. The Slide component should be contained in a div with the class "profile-slide-container", but I'm unsure how to achieve this. Below is the co ...

Prevent Xdebug from processing multiple requests

One recurring issue I encounter in my app is calling an API endpoint every 60 seconds. However, when I attempt to debug using Xdebug, stepping through the controller associated with that endpoint often takes longer than a minute. This results in another re ...

Microphone Malfunction: Abrupt End of Input Detected

I have been experimenting with SpeechRecognition to incorporate microphone functionality into one of my projects. However, when I check the Chrome Console, it displays the error message: Unexpected end of input const speechRecognition = window.webkitS ...

How can I declaratively bind the properties in Dojo's _hasDropDown method?

UniqueSearchComponent.html: <div class="${baseClass}"> <div data-dojo-type="dijit/_HasDropDown" data-dojo-props="dropDown: 'containerNode'"> <div data-dojo-type="dijit/form/TextBox" name="${SearchViewFieldName} ...

Encountering an error when sending data from a React application to a Flask server: Unhandled Promise Rejection - Unexpected < token in

Despite looking through various responses on this forum, I'm still encountering the same issue. My JSON is properly formatted and does not contain any HTML tags. I've tried using double quotes instead of single quotes for 'Key', but it& ...

Ways to initiate JavaScript event upon clearing input form field

I'm working on creating a dynamic search feature. As the user types in the search box, JavaScript is triggered to hide the blog posts (#home) and display search results instead (the specific script for this is not shown below). However, when the user ...

Creating a custom function in JavaScript to interact with the `windows.external` object specifically for use

In my current project, I am facing an issue with JavaScript file compatibility across different browsers. Specifically, I have a JavaScript file that calls an external function (from a separate file) using windows.external, like this: windows.external.se ...