jasonmzx
jasonmzx

Reputation: 517

JQuery, how can I call another JQuery function that's (id).on(click, function)

essentially I'm trying to run a JQuery on input function by calling it from another JQuery function while also running some code on the second function.

This is function SearchUser, its activated when the HTML ID: sm_to_usr's input changes.

    $('#sm_to_usr').on('input', function SearchUser() {
      $.ajax({
        url: 'sm_uf',
        type: 'get',
        data: {
          sm_to_inp : $('#sm_to_usr').val()
        },
        success: function(response) {
          var sm_out = response.sm_output
          console.log(sm_out.length + " is the length of sm_out arr");
          if (sm_out.length < 4) {
            $('#sm_user_disp').css('overflow-y','hidden');
            $('#sm_user_disp').css("height", (sm_out.length * 5).toString() + "vh")
            //else set too 22vh..
          } else {
            $('#sm_user_disp').css('height', "22vh");
            $('#sm_user_disp').css('overflow-y','scroll');
          }

          $('#sm_user_disp').empty();
          var j;
          for (j = 0; j < sm_out.length; j++) {
            $('#sm_user_disp').append('<p class="sm_users">'+sm_out[j]+'</p>');
          }
        }

      });

    });

Now, this first function essentially generates a dropdown menu of all users with matching names to the search query. When some clicks one of those usernames, it preforms a function that sets the Input of sm_to_usr to the specific username.

Here the first 2 lines execute well, and set the input value, but the SearchUser function doesn't notice a change in input, so I'm trying to call it manually.

    $(document).on('click', '.sm_users', function(){
      var $user = $(this).html();
      $('#sm_to_usr').val($user);
      SearchUser();
    });

HTML:


                  <input id="sm_to_usr" autocomplete="off" placeholder="Search users.." value="">
                  <br>
                  <!-- Displays a list of valid users while the client types in a name -->
                  <div id="sm_user_disp"></div>

Upvotes: 0

Views: 37

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

Changing the value programmatically won't trigger any event.

$('#sm_to_usr').val($user); // Does NOT trigger an input on sm_to_usr

But you can trigger it like so:

$('#sm_to_usr').val($user).trigger("input");

Upvotes: 1

Related Questions