Alex Coplan
Alex Coplan

Reputation: 13361

How to detect whether a form input's value has changed since set

I'm currently creating a custom-built CMS. The specific section I'm working on is to do with managing a photo gallery. On the page where the user can update details in a certain album, I use jQuery's $.ajax to do a lot of the updating.

For example, each image has a caption field next to it, and I bind the focusout event to my ajax call, which works really nicely, and makes it quick for the user to tab through and update all the captions for the photos.

However, since I am binding the focusout event, it is likely to be called a lot, especially when it isn't necessary. Say for example, they tab through three fields which they don't change. A $.ajax call will be made for each time they pressed tab, even though they haven't changed the input value.

So, my question is how can you store and detect if a value is different from what it was originally (or the last time an ajax call was made)?

Can this be done using jQuery's .data()?

Upvotes: 0

Views: 1747

Answers (3)

Alex Coplan
Alex Coplan

Reputation: 13361

Solved using very simple jQuery:

in document.ready:

$('.caption_field').each(function() {
    var startval = $(this).val();
    $(this).data('setval',startval);
});

Then when the ajax call is made:

if (caption == $(this).data('setval')) return; // not changed

When the call returns successful:

field.data('setval',caption);

Upvotes: 0

Craig M
Craig M

Reputation: 5628

The key to doing this properly is keeping your data separate from the input field. When the user blurs the input box, you can check the value against the in-memory data. If the values differ, you perform the ajax request. If not, you do nothing and save that round trip.

You could write that all yourself, but there are quite a few frameworks that have popped up in the last few years that do this very well. Among them:

Backbone.js

Spine.js

Knockout.js

Backbone seems to be the most popular of these.

Upvotes: 1

lontivero
lontivero

Reputation: 5275

You have to have the original values stored in input type hidden and compare original and current values in each focusout event.

Upvotes: 0

Related Questions