Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an issue when I use jQuery to handle the trigger of change on my drop-down.

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 one running smoothly, but the second one is not triggered when I start the browser, but after I refresh my site, it works.

Do you have any idea?

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

-- Edit: @JanR & Cheery: It seems like this:

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

I've used Rails 4.1 and arr is an array contains numbers.

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

I put the JS code inside a script tag and it works in both case, but when I put it in the assets folder, the issue happens.

Thank you for your quick replies!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

I recommend using case 1, since it is composed document to load change event, if you choose the elements are dynamically generated, use case 1 will be effective.

Also jquery doc said, .change () is a shortcut for .on ("change", handler), so I think eventually will use .on callback.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...