Mark
Mark

Reputation: 307

Detect when textbox value changes with jQuery

I have a 2 textboxes. In the first I type an unique id for a customer. When I tab out of this textbox it fires a query to my DB and fills the second textbox, which is the customer type.

When the value of the second textbox is updated from the DB (i.e. the value 'changes' from "" to the retrieved value) I want to grab that value and send it as a parameter to my second DB query.

I don't always know how long the first query takes to update the second textbox, so I want to perform the query once the value in the second textbox changes.

Looking at the jQuery .change() event, it appears it only fires when the textbox loses focus, yet in my design, the textbox never gains focus.

Ideally it would be great if I could detect when the second textbox value changes and then fire my 2nd query.

How is this possible?

Thanks! Mark

Upvotes: 1

Views: 2019

Answers (2)

David Thomas
David Thomas

Reputation: 253506

I'm not sure exactly what your Ajax call looks like, but you should be able to use trigger('change'), or simply change(), to trigger the change event-handling:

$('#input2').val(variableFromAjaxFunction).trigger('change');

Upvotes: 1

Matt
Matt

Reputation: 75327

In the callback for your first AJAX request (where you populate the second textbox), trigger the change event.

You'll probably have:

jQuery.ajax({
  ...
  success: function (response) {
      $('#textbox2').val(response);
  }
});

Just change it to:

jQuery.ajax({
  ...
  success: function (response) {
      $('#textbox2').val(response).trigger('change');
  }
});

Upvotes: 0

Related Questions