Ayla
Ayla

Reputation: 114

jQuery Autocomplete Select Trigger Event

Context: I'm using jQuery's autocomplete plugin to trigger a show/hide element beneath it. Problem: The event is only triggered when text is typed in the input box, and not when the tag is selected from the autocomplete list.

This is my code:

    <input name="Category" id="tags">
    <br>
    <div id="Sub_Level2">
        Sub Category
        <select name="SubCategory" required>
            <option value="1">Item 1</option>
            <option value="2">Item 2</option>
        </select>
    </div>

The div #Sub_Level2 is shown/hidden according to the text entered inside the input box.

 $('input[name=Category]').keyup(function () {
        if ($(this).val() == "Green")
            $('#Sub_Level2').show();
        else
            $('#Sub_Level2').hide();
    });

This works, however is the tag 'Green' is selected from the autocomplete box, the show/hide does not work. It only works when it is typed in.

How do I adjust this code to trigger the show/hide event of the #Sub_Level2 div when the user clicks a tag on the autocomplete box.

Thanks in advance.

Upvotes: 1

Views: 3072

Answers (2)

Harshal Sharma
Harshal Sharma

Reputation: 64

    $(document).ready(function() {
      $("#tags").autocomplete({
        select: function(event, ui) {            

          if (ui.item.value == "Green")
          $('#Sub_Level2').show();
        else
          $('#Sub_Level2').hide();
        }
      });
    });

    $(function() {
      var availableTags = ["Green", "Blue"];

      $("#tags").autocomplete({
        source: availableTags
      });
    });

Upvotes: 0

kamesh
kamesh

Reputation: 2424

You need to trigger the same keyup event in jquery autocomplete select callback function .. check this example FIDDLE:https://jsfiddle.net/kameeshwaran/m96nseh4/3/

$(document).ready(function(){
  $('input[name=Category]').keyup(function () {
        if ($(this).val() == "Green")
            $('#Sub_Level2').show();
        else
            $('#Sub_Level2').hide();
    });

    $( "#tags" ).autocomplete({
        select: function( event, ui ) {
          $("input[name=Category]").val(ui.item.value);
          $('input[name=Category]').keyup();
         }
    });
});

Upvotes: 2

Related Questions