In my Rails application i use a generic application.rhtml for all my pages. Amongst others, this code contains some jQuery code to manipulate my page
var $j = jQuery.noConflict()
$j(document).ready(function() {
// remove all alt-tags
$j("[alt]").removeAttr("alt");
// validate all forms
$j("form").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent() );
}});
});
The things i do in my document ready callback is simple: remove the alt attribute everywhere, so my tooltips will work on my links containing images, and if there is a form on the page i validate it.
Now for one form, i need to add special code, so that when a user fills something in a field, a select-box looses some options. The ideal place to do this, is in the document ready. But not for all pages. How do i solve this in some elegant way, and not use a different layout for that page.
I choose to use yield and content_for. Like this. Add the following line :
var $j = jQuery.noConflict()
$j(document).ready(function() {
// remove all alt-tags
$j("[alt]").removeAttr("alt");
<%= yield :script %>
// validate all forms
$j("form").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent() );
}});
});
and in my view i write:
<% content_for :script do %>
var allOptions = $j('#mention_thm_classification option').clone();
$j('#mention_thm_reference_local').change(function() {
var filter_txt = '.ref-';
if (!$j(this).val()) { filter_txt = filter_txt + 'empty'; }
else { filter_txt = filter_txt + 'filled'; };
$j('#mention_thm_classification').html(allOptions.filter(filter_txt));
});
<% end %>
So what i actually do is, check whether the value of a field changes. When it contains something a select-list with id mention_thm_classification is changed, and only the options with the correct class are kept.
For completeness, my select is built as follows:
<select name="mention[thm_classification]" id="mention_thm_classification" >
<option value='1' style='background-color: #b7f9e2' class="ref-empty " >Green</option>
<option value='2' style='background-color: #ffdebb' class="ref-empty " >Orange</option>
<option value='3' style='background-color: #ffbbc6' class="ref-empty ref-filled" selected="selected">Red</option></select>
So i have described a nice way to add extra code to my document ready function without needing a special layout-page. And experienced for the umpteenth time how great jQuery is.
