.change () vs .on ("change", handler) in jQuery

I have a problem when I use jQuery to handle a change trigger in a drop down list.

I use 2 pieces of code:

//---------- Case 1 $(document).on("change", "#drop-down-id", function () { alert(this.value); }); //----------Case 2 $("#drop-down-id").change(function () { alert(this.value); }); 

The first works smoothly, but the second does not start when the browser starts, but after updating my site it works.

Do you have any ideas?

My jQuery version is 1.11.1, and I tested on Chrome 38, Firefox 32, and IE 11.

- Edit: @JanR and Cheery: Sorry, I can't post the original, but it looks something like this:

 <select id="drop-down-id"> <% arr.each do |option| %> <option value="<%= option %>"><%= option %></option> <% end %> </select> 

I used Rails 4.1 and arr - the array contains numbers.

- Edit: I found out that the problem came from Asset Pipeline of Rails and not from jQuery.

I put the JS code inside the script tag, and it works in both cases, but when I put it in the resources folder, the problem arises.

Thanks for your quick answers!

+5
source share
2 answers

I recommend using case 1, since it consists of a document for loading the change event, if you select the elements generated dynamically , using option 1 will be effective.

Also the jquery doc said: .change () is a shortcut for .on ("change", handler), so I think that it will ultimately use .on callback.

+2
source

In case you bind a change event at the document level to an element of that part of the document. At this stage, it does not matter whether it exists or not (say that it was created later or loaded later).

In the second case, you bind the event to an element that must already exist in the DOM, or the binding will fail. What can happen is that your javascript is run before the element has been loaded onto the page.

Try wrapping case 2 in $ (document) .ready () like this:

 $(document).ready(function(){ //----------Case 2 $("#drop-down-id").change(function () { alert(this.value); }); }); 

This ensures that your javascript will not fire until the DOM is ready.

-1
source

Source: https://habr.com/ru/post/1205654/


All Articles