Autofilling an input field using JQuery

Jack022 :

I have the following form:

<form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val'>
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

And the following function to handle live search:

$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('http://127.0.0.1:8000/tst/', function(data) {
    console.log(data)

    let data = {
        "results": [
          { "item": "First",  "id": "1847" },
          { "item": "Second", "id": "4442" },
          { "item": "Third",  "id": "3847" }
        ]
    };

    //LIVE-SEARCH
    $(() => {

      $('#item').typeahead({
        source: {
          data: data.results.map(record => record.item)
        },
        callback: {
          onInit: function($el) {
            console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
          }
        }
      });

    });
    //END LIVE-SEARCH

  });
});

I want to add another function to fill the default value of the input field item-id according to what the user chooses on the input field item. So, for example, if the user writes First, JQuery should set the default value of item-id to 1847 (see my previous block of code).

How can i do that? Am i supposed to do that inside my live search function or should i use another function?

Bilel :

Looking at your code, I assume you are using Bootstrap Typeahead which uses an updater callback that we can use in this situation.

I hosted this static Json to bring a solution with a close syntax.

Solution 1 : Using Bootstrap Typeahead (may be useful to someone else)

$(document).ready(function(){

    $('input#item').typeahead({
        
	    source:  function (query, process) {
        return $.get('https://api.myjson.com/bins/hi1oo', function (data) {
        		//console.log(data);
        		//data = $.parseJSON(data);
	            return process(data.results);
	        });
	    },
        display : 'item',
        displayText: function(data){ return data.item;},
        val :  function(data){ return data;},

        updater: function (data) {
            
            $('#item-id').val(data.id);
            return data.item;
            }
        
	}); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" integrity="sha256-LOnFraxKlOhESwdU/dX+K0GArwymUDups0czPWLEg4E=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val' autocomplete="off">
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

P.S : If your json is a result of a real-time search query where you look for item names and get this kind of data. Then you better change the source into something like following :

source:  function (query, process) {
return $.get('inc/ajaxh.php', { query: query }, function (data) {
        return process(data.results);
    });
},

Solution 2 : using jQuery Typeahead

This one uses the callback onClickAfter. Notice that I made some changes on how you are mapping your data' response array and choose what to be displayed then use the item.id in the callback function.

$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('https://api.myjson.com/bins/hi1oo', function(data) {

    //LIVE-SEARCH
    $(() => {

      $('#item').typeahead({
        source: {
          //data: data.results.map(record => record.item)
          data: data.results
        },
        display: ["item"],
        callback: {
            //I called it itemx to avoid confusion with available "#item"
            onClickAfter: function (node, a, itemx, event) {
                $('#item-id').val(itemx.id);
                //alert('click');
        }
    }
      });

    });
    //END LIVE-SEARCH

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha256-q6QA5qUPfpeuxzP5D/wCMcvsYDsV6kQi5/tti+lcmlk=" crossorigin="anonymous"></script>
<form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val'>
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26250&siteId=1