Can I/How to bind jQuery events to form element load when loading Rails partials?
I want to call a function whenever a form element (hidden field, specifically) with a certain class loads. This:
$('.has_other').ready(function(){
alert($(this).value);
});
works fine on the initial page load, but when I reload the form partial that contains the element with the "has_other" class (for editing an element using the same form), the event does not get called again. Is there a way in jQuery to cause this function to be called on all loads of the hidden field, including reloads/loads of partials within the existing page?
Thanks in advance!
Edit: I render the partial like this in my controller:
page.replace_html 'secondary_publication_entry', :partial => 'publications/form'
Edit 2: Here is more specific code:
$j('.has_other_hidden').live('ready', function(){
alert($j(this).value);
});
Have also tried
$j('.has_other_hidden').ready(function(){
alert($j(this).value);
});
and
$j('.has_other_hidden :hidden').live('ready', function(){
alert($j(this).value);
});
The only one of these that causes any alerts is .ready(), which does not cause the alerts on partial load/reload, which is what I would like to happen.
I 开发者_如何学JAVAguess I could call a function that calls ready() again when I reload each partial - I'm not sure how to do this though (call a jquery function from a rails controller).
Thanks for the answers!
Edit 3: I've tried live('load',...) and live('ready',...). Neither work here :(
Try looking at the live method of jQuery library. I think this will work
$('.has_other').live('load', function(){
alert($(this).value);
});
If that doesn't work try firing the event after the ajax request that reloads that partial.
This is kind of gross, but if live()
isn't working, you could undo and redo all the bindings manually. Example:
function bindMyStuff() {
$('a').unbind('click');
$('a').click(funciton() {
alert("I've been clicked!");
}
}
$(document).ready(function() {
bindMyStuff();
});
Then your partial could call bindMyStuff()
within script tags.
Is this field hidden? If it is $('.has_other') will only return fields that are visible.
$('.has_other :hidden')
should get the hidden element.
精彩评论