3

Follow w3schools

The triggerHandler() method is similar to the trigger() method. Except that it does not trigger the default behavior of an event (like form submission) and it only affects the first matched element.

But I test with 2 input tag and use

$("input").triggerHandler("select");

then both of them are affected . Here's my code:

HTML:

<input type="text" name="FirstName" value="Hello World" />
<input type="text" name="FirstName" value="Hello" />

JavaScript:

$(document).ready(function(){
  $("input").select(function(){
    $("input").after(" Input select event occured!");
  });
  $("button").click(function(){
    $("input").triggerHandler("select");
  });
});

Live Copy on jsFiddle

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
Toan Nguyen
  • 1,043
  • 3
  • 13
  • 24
  • +1. Some notes: 1. Always include the relevant code and markup **in the question itself**, don't just link: http://meta.stackexchange.com/questions/118392/add-stack-overfow-faq-entry-or-similar-for-putting-code-in-the-question I've done it for you on this occasion, as you're new. :-) 2. Why use w3schools when [jQuery's own documentation](http://api.jquery.com) is so good and w3schools' documentation tends to be incomplete? 3. Your fiddle includes both MooTools and jQuery, which can tend to confuse things (although not in this case). Look to the left to see what libraries you're including. – T.J. Crowder Nov 10 '12 at 08:35

1 Answers1

3

The event is only being triggered on the first element. Your code, though, is outputting two lines when that happens:

$("input").after(" Input select event occured!");

That line, run once, will append the text after all matching input elements. Since there are two matching elements, you see the line twice even though the event only fired for the first element.

Just change that one line to

$(this).after(" Input select event occured!");

...and you'll see the output appended only after the element on which the event was triggered. Live Copy, with just the change above and removing the option to include MooTools on the page.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875