Johann
Johann

Reputation: 29867

Javascript: change event getting fired when input field loses focus

I have input fields on my page and I detect when the user types something to enable the Save button. I also have enabled a shortcut Ctrl + S to let the user save. Whenenever data is saved, the Save button is disabled.

However I have a dilemma. If the user changes the text in an input field, does a Ctrl + S and then moves to another input field using the mouse, the "change" event gets fired for the input field that the user changed and this in turn causes the Save button to get enabled again. The Save button should not be enabled because no changes have taken place after doing a Ctrl + S. What it appears is that the change event is fired not just with changes in text but also when the focus is moved to another field.

$("input.SaveMe").live('keypress change', function ()
{
    // Code goes here to enable Save button
});

How can I prevent the change event from taking place after saving. I thought of using some kind of flag but I can't figure out how.

Upvotes: 0

Views: 713

Answers (2)

Johann
Johann

Reputation: 29867

Removing the detection for "change" takes care of the problem but this now prevents users from pasting text into a field and detecting the paste as a change. To fix that use:

$(document).bind('paste', function (e)
{
  // Add code to update flag to indicate data changes and enable the Save button.
});

Upvotes: -1

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46728

You can ignore the event when that particular input is not in focus, in the following manner.

$("input.SaveMe").live('keypress change', function() {
    if (!$(document.activeElement).id == 'id_of_input') return; //if (!$(document.activeElement).hasClass('SaveMe')) return;
    // Code goes here to enable Save button
});

Upvotes: 2

Related Questions