Search code examples
jqueryjquery-selectors

jQuery selector for setting a value of an input based on the current context


I have several inputs that I would like to offer the same jQuery Autocomplete function on.

When the user selects an option, I would like to set the value of the corresponding text box to the id of the selection.

<script>
      $(function () {
          $(".batter").autocomplete({
              source: function (request, response) {
                  $.ajax({
                      url: "getplayersAjax.aspx",
                      dataType: "jsonp",
                      data: {
                          term: request.term,
                          league: 11
                      },
                      delay: 400,
                      success: function (data) {
                          response(data);
                      }
                  });
              },
              minLength: 3,
              select: function (event, ui) {
                  $("#birds1id").val(ui.item.id);
              }
          });
      });
  </script>
 
<div class="ui-widget">
  <input id="birds1" class="batter"><input type="text" id="birds1id" />
</div>
<div class="ui-widget">
  <input id="birds2" class="batter"><input type="text" id="birds2id" />
</div>
<div class="ui-widget">
  <input id="birds3" class="batter"><input type="text" id="birds3id" />
</div>

The code works fine for the birds1/birds1id pair.

However, I am struggling to work out how to get the function to work for the second birds2/birds2id pair (and other pairs that I will add later) without having to replicate the autocomplete function.

I assume the #birds1id selector needs to be replaced with something more generic but I am at a loss as to how to do it. [jQuery beginner here] I tried using 'this' but couldn't seem to get it work.


Solution

  • You are correct that you need to replace the hard-coded #birds1id selector. You can obtain a reference to the changed input from the event object that is the the first argument to your select handler: event.target. Once you have the element, you can query for its sibling and set the value. Note: I would think you need to use ui.item.value to get the value, rather than the ui.item.id you have in your code, but maybe I am wrong. The success handler becomes:

    function(event, ui) {
      const $target = $(event.target);
      const $sibling = $target.next();
    
      $sibling.val(ui.item.value);  
    }
    

    Here is a fiddle for reference.