0

I am building a rails app where I want to simply fire code when a user selects an option on a element (unobtrusively). I have read that the most supported way of doing this is by attaching the element directly to the change event:

$('#country_selection').change(function() { alert('it works'); });

However, for me, this is not working. If I put it in the console, it works just fine. However, putting it in the js file of my view, it does not work. I know my js file is being loaded because inserting a simple alert('in the js file'); returns just fine. The other strange part is that using the live method works:

$('#country_selection').live('change', function() { alert('hello'); });

However, I do not want to do this b/c it is not as supported. The other option I tried which does not work is the 'delegate' method:

$('#country_selection').delegate('change', function() { alert('hello'); });

Why isn't my change function working?

4

1 回答 1

2

If you have a select element like

<select id="my-select-box">
  <option value="1">First Value</option>
  <option value="2">Second Value</option>
</select>

Then the following Jquery code should work

$('#my-select-box').change(function() {
  alert("hey, i got changed");
 });

It is imperative that the DOM is loaded before JQuery binds your code to the selector. To do this, ensure that you have your code within an anonymous function as such:

jQuery(function(){

  $('#my-select-box').change(function() {
    alert("hey, i got changed");
   });

});

This ensures that the DOM is loaded before the JQuery executes and tries to bind. Otherwise the JavaScript will execute before the element is loaded, and it will not execute correctly.

于 2012-08-14T13:18:48.243 回答