Just what it says. I'm trying to do some simple drop down filtering with jquery, and my function doesn't get executed on page load. Here's what I've checked:
- added a console.log to verify
- used document.ready to call function
- It's getting loaded through sprockets in app.js
- it's listed in dev console, and I don't get any resource not found errors
Here's the crazy part : everything works perfectly after one refresh. Console.log comes back and reports the listener has been attached to the select element and everything is roses.
Any ideas why?
EDIT here's the entirety of the js (there may be a better way of doing this, also open to suggestions):
//unrelated JS
$(document).ready(function(){
$("#user_state_code option").unwrap();
$state_copy = $("#user_state_code").children().clone(true);
$("#user_country_code").change(function(){
console.log("state filter called");
filterStates($("#user_country_code").val());
});
$("#user_country_code").change();
});
function filterStates(countryCode){
$("#user_state_code").html(
$state_copy.get().filter(function(d){
var currCountry = String(d.value);
return currCountry.slice(0,2) == countryCode;
})
);
}
Epilogue
Here's what needed to be fixed (thanks to @Rain who put me in the right track, and prompted me to find this amazing resource: Rails 4 turbo-link prevents jQuery scripts from working
var ready = function() {
$("#user_state_code option").unwrap();
$state_copy = $("#user_state_code").children().clone(true);
$("#user_country_code").change(function(){
console.log("state filter called");
filterStates($("#user_country_code").val());
});
filterStates($("#user_country_code").val());
};
function filterStates(countryCode){
$("#user_state_code").html(
$state_copy.get().filter(function(d){
var currCountry = String(d.value);
return currCountry.slice(0,2) == countryCode;
})
);
}
$(document).ready(ready);
$(document).on('page:load', ready);