Using jQuery UI autocomplete to insert the description of the selected item into a text field

Currently, I have a functional autocomplete text box with the following code:

 $('#material_number').autocomplete({
     source: function(request, response) {
         $.ajax({
             url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
             dataType: "json",
             data: {
                 search: request.term,
                 maxRows: 10
             },
             success: function(data) {
                 response(data);
                 console.log();
                 //need to append material_description to a textbox here
             }
         })
     }
 });

I am attempting to display the material_description value returned in a textbox named txtMaterialDescription. Despite researching various examples on this platform, I have not been successful in achieving this functionality. Essentially, when a user selects a part number from the autocomplete list, the description field should automatically populate with the relevant part number's description. Could someone assist me with this and guide me in the right direction?

Thank you in advance.

Sincerely, JC

Answer №1

If you want to capture either the focus event or the select event, you can do so with the following code:

focus: function(event, ui) {
    $("#textbox").val(ui.item.someProperty);
}

In case your JSON data comprises objects structured like

{label: ..., value: ..., someProperty: ...}
, you can simplify it with this code snippet:

source: function(request, response) {
    $.ajax({
        url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
        dataType: "json",
        data: {
            search: request.term,
            maxRows: 10
        },
        success: response
    });
}

If your data doesn't have a similar structure, you can transform it using jQuery.map as shown here:

source: function(request, response) {
    $.ajax({
        url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
        dataType: "json",
        data: {
            search: request.term,
            maxRows: 10
        },
        success: function(data) {
            response($.map(data, function(item) {
                return {
                    label: item.productName,
                    value: item.productCode,
                    someProperty: item.productDescription + item.productPrice
                }
            }));
        }
    });
}

Answer №2

If you want to focus on a specific item and load its details, you can use the focus option in your code like this:

   focus: function(event, ui) {
            $(this).val(ui.item.label);

 //perform an ajax call here for the currently focused element
  // once the call is successful, you can execute the following

  //display detailed information
            $("#tags").empty();
            $("#tags").append("Details for "+ui.item.label);

            return false;
        },

For more information and examples, check out this jquery autocomplete example.

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

The XML information vanished during the transformation into JSON format

After converting XML to JSON using multiple conversion libraries, I noticed that the property name attributes and Item name attributes were lost. Why is this happening? Does anyone have suggestions on how I can modify my XML to make it more compatible for ...

Make the div disappear after a specified time

Does anyone know of a code snippet that can make a couple of div elements fade out after a specific time period? Currently, I have the following example: <div id="CoverPop-cover" class="splash"> <div id="CoverPop-content" class="splash-center"> ...

Converting Ajax to JSON with Jquery offline and Manifest for enhanced offline web applications

Looking to create an offline web application, I'm in the process of transitioning from Ajax to JSON using JQuery offline. Here is the initial Ajax code: $.ajax({ url: contentpage, data: contentpagedata, cache: false }).done(function( html ) { ...

Conditional serialization in Json.NET based on the type of the object being serialized

I am aware that Json.NET allows for conditional serialization by using ShouldSerialize{PropName} Is there a way to prevent the serialization of an entire type without changing the type that references it? For example: public class Foo { public boo ...

"Exploring the world of Highcharts: A guide to loading data using

I am experiencing an issue with my application where highchart is not loading data via ajax. I have checked a demo provided on the highcharts website for loading highcharts via ajax, but it also seems to be not working. You can find the demo at this URL: h ...

What is the process of transforming a list of arrays, which is in JSON format, into Dart?

Having trouble with the JSON_ANNOTATION feature when dealing with a json that contains nested arrays. Uncertain about how to convert the paths in the array into a single Paths object. Maybe something like this, but it doesn't seem to handle multiple ...

What is the best way to prevent the click event of a container div from triggering when clicking on elements within the container using JQuery

For example: <div class="wrapper"> <div class="inner">Clicking me won't trigger the wrapper click event</div> </div> $('.wrapper').click(function(){ // Do something with the wrapper here }); However, when I cli ...

Effortless AJAX/jQuery solution for displaying live file updates while copying

As I delve into the world of Ajax/jQuery, my current focus is on setting up a test environment for the following scenario: The server needs to recursively copy an entire folder from one location to another. The client should then display the list of copi ...

Is it possible to include an if or else condition in jQuery JSON response?

I have an issue with adding my Jquery JSON response to a data table. However, I need to implement if conditions based on the day. Can you provide me with an example of how to do this? Specifically, I need to use conditions in the data.hours.day field. Th ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

Python: Exploring JSON Data

Is there a way to extract data specific to a district (such as Nicobars, North and Middle Andaman...) from ? I am trying to extract the Active cases by simply searching for the district name without having to specify the state every time. Currently, I&apos ...

Activate all inactive input and selection elements

I need a solution to enable all disabled input and select elements before submitting the form in order to retrieve the values of those disabled elements. Here is what I have tried: function enable() { $('input[type="text"], input[type="chec ...

Returning to a page that has been scrolled down and contains dynamic content loaded via ajax

Currently, my page utilizes ajax to load dynamic content. However, I have noticed a discrepancy in how Firefox and Internet Explorer handle the scrolling position when navigating back using the browser's back button. Firefox retains the scrolled posit ...

Fetching PHP file in WordPress with ajax

Is it possible to use AJAX to request PHP files like "single.php" or "page.php" in WordPress instead of using functions? Thank you. ...

What is the best way to eliminate base tags from jQuery mobile scripts?

In jQuery Mobile, how can I remove the base href tags from the page and disable base href? Code Snippet: // Function to test for dynamic-updating base tag support function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + l ...

Transforming form inputs into JSON structure

<form name = 'test' > <input type='text' name = 'login'> <input type='email' name = 'email'> </form> When I try to convert the form data using JSON.serialize($(form)).serial ...

The contenteditable div's selectAll feature doesn't function properly when it gains focus

I'm working with divs in a table structure and here's an example: <div contenteditable="true" onfocus="document.execCommand('selectAll',false,null)">Something</div> Clicking on a div to focus works perfectly, selectin ...

Reveal and conceal grid elements upon clicking embedded links

I'm attempting to toggle the visibility of div content upon clicking a link. I've tried using a similar approach as shown in http://jsfiddle.net/fXE9p/, but unfortunately it didn't work for me. <body> Clicking on a button should m ...

The Jquery change event binding does not function properly when dealing with dynamically generated content

When attempting to attach a change event to a dynamic input checkbox element, I encountered some unusual behavior... The following code is successful : $("form").on('change', 'input:checkbox.checkbox_main', function () { c ...

What could be the reason that Ng Repeat fails to work when a button is triggered from a separate form

I have an HTML table that includes an ng repeat directive and two buttons. The first button opens a modal with a form to create a new user. When I click save, it adds the new user to the list. The second button is within the same form and also adds a user. ...