Automatically filling in related information in multiple input fields after choosing a value in a specific input field using JavaScript

My horizontal form is dynamically generated using JavaScript, with each input field having a jQuery autocomplete that retrieves data from a database using the $.get method.

I'm looking to automatically populate the second input field with the corresponding value when a selection is made in the first input field. The rows and autocomplete functionality are cloned as the rows are created.

In the scenario depicted in the image below, upon selecting the category set, I want the value field to be filled automatically:

https://i.stack.imgur.com/JQwDA.png

I have successfully implemented the autocomplete feature but am struggling to auto-fill the second input field.

function loadcategorysetvalue(table, tabdata){
    var catsetlov = [];
    var catvalov = [];
    
    $.get("URL", function(response){
        catsetlov = response;
    }).done(function(){
        var row = null;
        var newId = 1;
        
        for(var i = 0; i < catsetlov.length; i++){
            newId++;
            
            row = insertrow(table(table, tabdata, "categories"));
            cell = row.cells[0];
            cell.children[0].value = catsetlov[i];
            setcatvalue(catsetlov[i]);
            addbtn(row);
            
            var id = cell.children[0].getAttribute("id");
            var newId = id + "_" + newId;
            cell.children[0].setAttribute("id", newId);
            
            $('#' + newId).autocomplete({
                source: catsetlov,
                minLength: 0
             }).focus(function(){
                $.get("url", function(response){
                    catsetlov = response;
                });
                $(this).autocomplete("search", "");
            });
        }
    });
}

Answer №1

For an easier solution, consider setting the other input fields on the "select/change" event of the autocomplete field. Here's an example:

var myList = [{"label":"Value one","id":"1"},{"label":"Value two","id":"2"},{"label":"Value three","id":"3"}];

$("#txtAutocomplete").autocomplete({
  source: myList,
  select: function(event, ui){
    if(ui.item){
      $("#hiddenField").val(ui.item.id);
      return ui.item.label;
    }
    else{
      $("#hiddenField").val('');
    }
  },
  change: function(event, ui){
    if(ui.item){
      $("#hiddenField").val(ui.item.id);
    }
    else{
      $("#hiddenField").val('');
    }
  }
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>
  Start typing something like "Val.."
</p>

<input type="text" id="txtAutocomplete">
<input type="text" id="hiddenField" disabled="disabled">

I trust this explanation proves beneficial to you. Farewell.

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

Exploring the world of web scraping by using Python to loop through HTML elements

Created a Python script to extract information from the website regarding its asset listings. So far, I have successfully retrieved the name of the first coin "Bitcoin," but I'm unable to get the ticker. With 27 pages on the site, each containing 40 ...

Error: Property 'config' cannot be accessed because it is null

Upon transferring my Angular project from my local computer to a Linux server, I attempted to launch the project using ng serve but encountered an issue where it opened a new file in the console editor instead. After some investigation, I tried running np ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Issue with jQuery Ajax not functioning properly across domains in Internet Explorer 9

I am facing an issue accessing a REST web service through jQuery. The Access-Control-Allow-Origin is correctly set to * as seen in Firebug, and Chrome/Firefox have no trouble accessing it. However, Internet Explorer seems to be causing trouble. I have gon ...

When attempting to execute a script that includes document.write, it will not function as expected

Our web program is utilizing ajax and jquery, specifically Netsuite. I've been attempting to adjust elements on a page using document.ready and window.load methods in order to load an external script onto the page. Regardless of whether I load this ex ...

Asking for information regarding RESTful API

Could you please assist me in identifying the most suitable technologies for integrating a RESTful API into an HTML and CSS website? The primary objective is to enable the website owner to easily log in and add news entries about their business. Addition ...

Develop a JavaScript library for use in the npm ecosystem

I have developed a minimalist JavaScript library that includes common functions: !!window.JsUtils || (window.JsUtils = {}); JsUtils = (function () { "use strict"; return { randomHex: function (len) { var maxlen = 8; ...

What are the steps to implement the jQuery slide menu effect on a website?

When visiting the website , you may notice a symbol positioned in the top left corner of the site. By clicking on this symbol, a sleek div will slide out. How can this type of animation be achieved through javascript or jquery? ...

The use of JQuery repeating fields can cause disruptions to the Bootstrap layout when removing rows

I have been struggling with a form that contains multiple fields that need to be repetitive. My current code is functional, but I'm encountering an issue where clicking on any remove button other than the first one causes the fields in the row to rear ...

Adjusting the height of flex items to 100%

I'm currently diving into the world of flexbox by exploring various tutorials. Here's an example I created without utilizing Flex. Instead, I relied on float:left. Check out the example: https://jsfiddle.net/arhj8wxg/4/ I attempted to convert t ...

Utilizing AJAX and PHP for dynamic changes based on listbox selection

Is there a way to make the query run whenever a selection is made from the listbox? if(isset($_POST['select'])){ $newselection=$_POST['select']; $query = "SELECT count(*) FROM listings where description=" . $newselection. ""; $r ...

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

Make sure the top edge of your Bootstrap 4 dropdown menu is perfectly aligned with the bottom edge of your

Trying to make a Bootstrap 4 navbar dropdown display right below the navigation bar, but it consistently shows slightly above the bottom edge of the navbar. Is there a way to make this happen without fixing the height of the navbar and using margin-top fo ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

Discovering the base color using a hexadecimal color value in C#

When working with a Hex color code in C#, how can you determine if the color falls under the categories of Red, Green, Yellow, Pink, Orange, or Blue? ...

The data list is failing to retain previous elements as new ones are incorporated

I have a list for uploads, and whenever I upload new data, the old data in the list gets removed. However, I want to display all the data together. How can I resolve this issue? const [fileList, setFileList] = useState<AddedFile[]>([]); const beg ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

"Maximizing efficiency with Jquery and handling multiple AJAX requests simultaneously on a

Thumbnails are displayed on a page in the following manner: <div id="credits"> <a href="largeimage1.jpg" alt="credits1.php"><img src="thumb1"></a> <a href="largeimage2.jpg" alt="credits2.php"><img src="thumb2"></a> ...

Curious about how to swap the positions of these two divs?

After wrapping them in divs and adding inline-block to both elements to display them side by side, I'm now exploring options to switch their positions. Specifically, I'd like the right element to be on the left. Any ideas on how to achieve this? ...