jkupczak
jkupczak

Reputation: 3041

jQuery .on("change") running more and more times but I only want it to run once

I'm trying to detect changes to input text fields. Whenever the user changes something in an input I want to grab the new value and validate it. My problem is that the code I'm using appears to be running more and more each time. It will detect a change to an input once. But then the next time one input is changed, the code will run twice. Then three times, four times, and so on. What is it that I'm doing wrong?

Here is my HTML:

<div class="input-wrapper">
  <input name="clickthru1" type="text" value="input1">
  <input name="clickthru2" type="text" value="input2">
  <input name="clickthru3" type="text" value="input3">
</div>

And here is my jQuery:

$( ".input-wrapper" ).on( "focus", "input", function() {

  console.log("focus on input detected");

    $( ".input-wrapper" ).on( "change", "input", function() {
      console.log("change to value detected");
    });

});

And here is a link to the codepen: http://codepen.io/jimmykup/pen/yYvbzK

Upvotes: 1

Views: 825

Answers (3)

Dmytro Pastovenskyi
Dmytro Pastovenskyi

Reputation: 5419

That is because you add 'on change' function to stack each time focus event is fired. So just put it out of focus functionality.

$( ".input-wrapper" ).on( "focus", "input", function() {
  console.log("focus on input detected");
});

$( ".input-wrapper" ).on( "change", "input", function() {
  console.log("change to value detected");
});

Upvotes: 3

Ibu
Ibu

Reputation: 43840

Everytime you focus on the input, a new change event handler is added to it. So the first time you focus, you will get one console log, the second time you focus you will get 2 , then 3 and so on.

The solution is to remove the nesting you currently have to only have one function call for each type of event:

$( ".input-wrapper" ).on( "focus", "input", function() {
  console.log("focus on input detected");
});

$( ".input-wrapper" ).on( "change", "input", function() {
   console.log("change to value detected");
});

Upvotes: 1

Igor
Igor

Reputation: 15893

Move change event assignment outside of focus event:

$( ".input-wrapper" ).on( "focus", "input", function() {
  console.log("focus on input detected");
});

$( ".input-wrapper" ).on( "change", "input", function() {
  console.log("change to value detected");
});

Upvotes: 3

Related Questions