Search code examples
javascriptjqueryarraysinputdetect

Jquery array of input IDs detect change


I have a question about detecting changes if inputs in array of input IDs.

For example I have an array of input IDs: var arrayOfInputs = ['#firstname', '#lastname', '#email', '#phone'];

My problem is that I want to detect any input change in these fields, BUT I don't want to write a bulky script code for each input field separately.

So question is: do there is a way to detect input change for all these inputs in array with one or two lines of code with jQuery?

Maybe I should use something other than array of IDs?


Solution

  • So question is: do there is a way to detect input change for all these inputs in array with one or two lines of code with jQuery?

    Yes:

    $(arrayOfInputs.join(",")).on("change", function() {
        // Here, `this` will refer to the input that changed
    });
    

    Live Demo:

    var arrayOfInputs = ['#firstname', '#lastname', '#email', '#phone'];
    $(arrayOfInputs.join(",")).on("change", function() {
      snippet.log(this.id + " changed");
    });
    <div><input type="text" id="firstname"></div>
    <div><input type="text" id="lastname"></div>
    <div><input type="text" id="email"></div>
    <div><input type="text" id="phone"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    Maybe I should use something other than array of IDs?

    Yes, give them all a common class or data-* attribute or something instead of listing IDs.

    Live Demo:

    $(".watch-me").on("change", function() {
      snippet.log(this.id + " changed");
    });
    <div><input type="text" class="watch-me" id="firstname"></div>
    <div><input type="text" class="watch-me" id="lastname"></div>
    <div><input type="text" class="watch-me" id="email"></div>
    <div><input type="text" class="watch-me" id="phone"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>