skip to Main Content

I am trying to get an input fields auto-populated, after a user selection an option from the drop down list, Using Jquery and JSON data received from a remote API call.

My goal is to have the end-user select a customer from the drop-down list(which is dynamically populated from the JSON data sent from the server) and then input fields populate with the customers details stored within the JSON Array.

Currently, the list loads and displays the customers name in the list.
I can then populate JUST the customers name into all of the text fields.

Edit: I can do this by making another call to the server or have the server render the page. But I only want my application to make 2 calls to the server, a GET to grab the JSON config file(s) for the app and then a PUT/ POST to update records. I am using Laravel 7.x for server side.

What I need is to be able to access the other Key/ Value pairs per customer.

This is my JSON output from the API call remove the first “data” top level remember, this seemed to allow me to sort them into the drop-down list otherwise it would all it just as one blank dropdown item.

 [
    {
        "CUID": 5,
        "can": "Acme",
        "pmfn": "Krillin",
        "pmln": "N/A",
        "pmpe": "[email protected]",
        "pmpn": "7343253228",
        "cct": "subContract",
        "cgt": "unarmedGuard",
        "created_at": "2020-03-29T19:12:47.000000Z",
        "updated_at": "2020-03-29T19:12:47.000000Z"
    },
    {
        "CUID": 15,
        "can": "test",
        "pmfn": "john",
        "pmln": "wick",
        "pmpe": "[email protected]",
        "pmpn": "55555555556",
        "cct": "directContract",
        "cgt": "armedGuard",
        "created_at": "2020-03-30T18:14:52.000000Z",
        "updated_at": "2020-03-30T19:44:56.000000Z"
    },
    {
        "CUID": 16,
        "can": "test43",
        "pmfn": "Jay",
        "pmln": "silent bob",
        "pmpe": "[email protected]",
        "pmpn": "7343253228",
        "cct": "directContract",
        "cgt": "unarmedGuard",
        "created_at": "2020-03-30T19:46:07.000000Z",
        "updated_at": "2020-04-02T01:29:10.000000Z"
    },

This is my current Jquery function

function populateCustomer (){
    let url = 'http://10.1.10.96:8080/api/customerList'; //sets the url of the JSON data

    let dropdown = $('#selectCustomerList'); // grabs the select element based on ID
    dropdown.empty();
    dropdown.append('<option selected="true" disabled>Customer</option>'); // adds a non-clickable default
    dropdown.prop('selectedIndex', 0);

// Populate dropdown with list of customers
    $.getJSON(url, function (data) {
          $.each(data, function (key, entry) {
            dropdown.append($('<option></option>').attr('value', entry.can).text(entry.can));
            if(data.Status=="Success") // checks if drop down list item was grabbed
                {
                  $("#can").attr('value', entry.can); //populates customer name inputer field from selected drop down item
                 $("#pmfn").attr('value', entry.pmfn);
                //  $("#pmln").attr('value', entry.pmln);
                }   
          dropdown.change(function () {
            $('#can').val(this.options[this.selectedIndex].value);
            $('#pmfn').val(this.options[this.selectedIndex].value);
            //$('#pmln').val(this.options[this.selectedIndex].text);
        });

      }) 

    });
}

populateCustomer();

The basic html

<label for="can"> Company Name</label>
<input type="text" name="customer_info" id="can" class="disabled" value="" readonly="readonly" />

<label for="pmfn">Property Mangers First Name</label>
<input type="text" name="customer_info" id="pmfn" value="" readonly="readonly" class="disabled" />

2

Answers


  1. Chosen as BEST ANSWER

    Okay finally figured it.

    First - in my php route I removed my code that stripped the original "data" top level member of the JSON file.

    My biggest mistake was assuming that $.getJSON automatically did the parsing to proper JS arrays for you. So once I figured it out, after that it was bouncing between makeArray and JSON.parse. Well first you need to make your JSON string a proper JavaScript string to use JSON.parse.

    So I went ahead and used strigify, and then used JSON.parse. After this I then was able re-add them to my drop-down list using proper JSON from the server.

    Here is where .change and selectIndex come in. I've read you can use .bind, but .change seems to work good for my case.

    The code then listens for the use to change the drop down list item -it then assigns i to the selected drop down list items appropriate index number -We need to subtract -1 from this number, because selectIndex starts the element index at 1 and not 0 like our JavaScript array of JSON data does.

    From this point we can then populate the fields/elements with a regular JavaScript object / array identified.

    Here is the Javascript function

    function populateCustomer (){
    	let url = 'http://10.1.10.96:8080/api/customerList'; //sets the url of the JSON data
    
    	let dropdown = $('#selectCustomerList'); // grabs the select element based on ID
    	dropdown.empty();
    	dropdown.append('<option selected="true" disabled>Customer</option>'); // adds a non-clickable default
    	dropdown.prop('selectedIndex', 0);
    
    	var custObj = $.getJSON(url, 
    	function(data){ //grabs JSON data from URL and runs callback functions to change the data to JS format
    		var x = JSON.stringify(data); //converts json data to string
    		//console.log(x);
    		x = JSON.parse(x); //parses proper json string to JS object
    		
    		//console.log(x); //logs all of the parsed data to console in proper JS format- SUCCESS
    		//console.log(x.data[5].can); // checks to make sure that I can access the object properly -SUCCESS
    
    		//populate dropdowns
    		$.each(x.data, function (key, prop) {
    		    dropdown.append($('<option></option>').attr('value', prop.can).text(prop.can));
    		});
    
    		// grabs the selected dropdown list items index ID
    		$('#selectCustomerList').change(function() { //functions listens for change on the dropdown box
        		var i = this.selectedIndex; // sets i to the selected index value
        		//console.log(i); // checks that we can grab the selected index int -SUCCESS!
        		/*
        		sets i to match the appropriaite array index. 
        		When using selectIndex the Index starts at 1 not 0 so we have to set it back -1
        		*/
        		i = i - 1; 
        		// appends the property managers first name element with data stored within the array
        		 $('#can').attr('value', x.data[i].can).text( x.data[i].can); // can - customer account name
        		$('#pmfn').attr('value', x.data[i].pmfn).text( x.data[i].pmfn); //pmfn - property managers first name
        		$('#pmln').attr('value', x.data[i].pmln).text( x.data[i].pmln);// pmln - property managers last name
        	});
    	});
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title> test </title>
      </head>
     <body>
     
      <fieldset>
       <select id="selectCustomerList" name="selectCustomerList">
          <option value="">Customer / Property </option>
        </select> <br />
      </fieldset>
      
      <fieldset>
        <label for="can"> Company Name</label>
        <input type="text" name="customer_info" id="can" class="disabled" value="" readonly="readonly" />
    
        <label for="pmfn">Property Mangers First Name</label>
        <input type="text" name="customer_info" id="pmfn" value="" readonly="readonly" class="disabled" />
    
        <label for="pmln">Property Mangers Last Name</label>
        <input type="text" name="customer_info" id="pmln" value="" readonly="readonly" class="disabled" />
      </fieldset>
     </body>
    </html>

    Hope this help anyone else!


  2. Thank you very much for posting your code, it’s clear, and it helped me for the same kind of exercice.

    I also looked at this short tutorial and finaly, I managed to make it work. But strangly, I didn’t need to parse the json code at all.

    Here is my working code :

     // I define all my inputs as variables
    let dropdown = $('#dci');
    let input1 = $('#family');
    let input2 = $('#interactions');
    let input3 = $('#cat');
    
      // Here we append the options frOm the json data first field
    dropdown.empty();
    dropdown.append('<option selected="true" disabled>Choisir un médoc</option>');
    const url = 'http://localhost/celderga/interaction.json';
      // I call my json file
    $.getJSON(url, function(data) {
       // for each row I grab the key and value of my first field
        $.each(data, function (key, entry) {
        dropdown.append($('<option></option>').attr('value', entry.DCI).text(entry.DCI));
       }); 
       // and then at each select' change I add the value of the others fiels in my inputs
       $('#dci').change(function()  {
         var i = this.selectedIndex; 
          i = i - 1; 
          input1.addClass(data[i].Famille);
          input2.text(data[i].Interaction);
          input3.text(data[i].CAT);
       });
    });
    

    It looks to me simplier and shorter, and don’t understand why you had to convert and parse json…maybe I’m doing wrong, but it works..

    The json file looks like this

    [{
           
    "DCI": "Antidépresseurs tricyliques",
    "Famille": "antidepresseurs",
    "Interaction": "Sub. du CYP2D6",
    "CAT": "Diminuer la dose du traitement concomitant"
    },{
      ...
    }]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search