1

For example I have the following code:

    $(".someSelector").change(function()
    {
        // Do something

        // Call function

        // console.log('test')

    });

The problem is, it is being called twice: whenever I lose focus of the input field and whenever the value changes.

I want it to be called only whenever the value changes.

Is there a way to ignore focus loss on the .change other than comparing old input value with the new input value?

Koeno
  • 1,493
  • 2
  • 16
  • 30
  • it will already be called only when the value changed in your case – xNeyte May 11 '15 at 08:01
  • 1
    Something is wrong with your question: `onchange` event does not fire if value is not changed. It fired on blur only if the value has changed after focus. – dfsq May 11 '15 at 08:02

2 Answers2

5

You should use the input event instead of change.

input is fired on each value change (including paste); changefires on blur when the value has changed.

$(".someSelector").on('input', function() {
    // Do something
});

The input event is supported by IE9+.

joews
  • 29,767
  • 10
  • 79
  • 91
1

Here's an answer from another question which I think applies to you as well:

You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.

$('#myTextbox').on('input', function() {
    // do something
});

If you use the change handler, this will only fire after the user deselects the input box, which may not be what you want.

Source: JQuery: detect change in input field

Community
  • 1
  • 1
mmvsbg
  • 3,570
  • 17
  • 52
  • 73