jQuery: How many times will .change() be called if I call it on a class of items?

281
November 21, 2016, at 6:36 PM

I have a mental block at the moment and am asking a silly question. Lets say i have this:

HTML

<input type="text" class="x"/>
<input type="text" class="x"/>
<input type="text" class="x"/>

jQuery

$(document).ready(function () {
     $(".x").change(function (e) {
        //functionality
     });
    $(".x").trigger("change");
});

How many times will the change event function be triggered? will it be triggered 3 times? one for each input? or only once?

Answer 1

It will be called once for each item in the .x selector.

In jQuery, something like this:

$(".x").trigger("change");

is implemented internally by getting the entire collection of elements that match the .x selector and then calling .trigger() for each separate element. Though there's no way to code it like this, you can think of it logically like this:

$(".x").each(function() {
    $(this).trigger("change");
});

In fact, if you look at the jQuery source code for the trigger method, you see this:

trigger: function( type, data ) {
    return this.each(function() {
        jQuery.event.trigger( type, data, this );
    });
},

So, you can see that it just loops over the jQuery collection triggering the event for each object in the collection.

Rent Charter Buses Company
READ ALSO
How can I call jquery Ajax call to Pass a Value from Client Side to Asp.Net Code Behind (.cs) file?

How can I call jquery Ajax call to Pass a Value from Client Side to Asp.Net Code Behind (.cs) file?

I am creating a Web Application using CK Editor which is server side control. [nnn]I am not using any server side control expect CK Editor.

334
ajax satuts cancelled after some attempts

ajax satuts cancelled after some attempts

im making and update in mysql table when button click, the problem is ajax jquery not working sometimes. It works fine and somehow after x attempts it stop working and stars cancelling my pettitions.

302
Show and hide content on hover with delay

Show and hide content on hover with delay

I need to do one thing. [nnn]I have element on webside.

349
Avoiding the duplicate selection of names in the dom using jquery

Avoiding the duplicate selection of names in the dom using jquery

Please look into the the attached jsfiddle. .

214