Application.js placement - Rails 3 & jQuery -
i'm dabbling jquery first time on first rails (3) project. i'm having trouble getting select statement's onchange fire when application.js include in header.
this current set-up:
header includes:
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" %> <%= javascript_include_tag 'rails' %> <%= javascript_include_tag 'application' %> <%= csrf_meta_tag %>
application.js
jquery('#location_country_code').change(function() { alert('hi'); });
my problem can onchange function fire if place application.js include @ bottom of page (ie: after select element). appears placing in header means event handler not set element not yet defined.
all tutorials on type of thing talk putting js code in application.js i'm assuming i'm missing fundamental.
thanks in advance help/advice.
you should encapsulate jquery in "document ready" block:
jquery(document).ready(function() { jquery('#location_country_code').change(function() { alert('hi'); }); });
which equivalent to:
$( function() { jquery('#location_country_code').change(function() { alert('hi'); }); });
this waits document loaded before assigning handler. otherwise, select not exist yet , handler not applied.
alternatively, use live
call instead:
jquery('#location_country_code').live('change', function() { alert('hi'); });
the live
function applies handler window , handles event when bubbles select. because of this, select element not need exist before apply it. helpful when create elements dynamically, want existing handlers apply them when created. result, cures issue elements not existing before page loaded.
however, practice wrap code in "ready" block in case, avoid unwanted side-effects.
Comments
Post a Comment