Pavlo K
Pavlo K

Reputation: 151

Detect if value was changed by jQuery

I have this code:

$('#inserted_advert_id').val(data['id']);
myFunction();

But I want to run myFunction() after input #inserted_advert_id will be changed. Now, when I run this script, input #inserted_advert_id is not changed (it is changed after myFunction() is execute).

How I can do it?

Upvotes: 1

Views: 28

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The simplest way to achieve this would be to manually raise a change event when you set the val() of the element:

function myFunction() {
  console.log('advert id was changed!');
}

$('#inserted_advert_id').on('change', function() {
  // any processing logic, if needed, goes here
  myFunction();
});

// somewhere else in your code base...
var data = { id: 'foo' }
$('#inserted_advert_id').val(data['id']).trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="inserted_advert_id" />

Upvotes: 1

Related Questions