I am new to rails trying to create an application to manage label set translations using Rails 3. I havenβt gone too far beyond forests as far as I know, I use the default Rails 3 javascript libraries (i.e. prototype, not jQuery )
I have a form for label set names, and the desired behavior is so that the names of all current label sets are populated in the drop-down list ( "label_sets"), and when you select one, this fills the text box :name( $('label_set_name')) and disables it. If a value is displayed in the drop-down list :include_blank, you can enter a new label set name. When the form is submitted, the text field :nameis included again, so its value will be actually saved.
This form performs the desired behavior, but I think there should be a way to refactor javascript to :onsubmitand :onchangeto another file and make it unobtrusive. I looked at the web material for creating unobtrusive javascript in Rails 3, but many honestly confused it and donβt know how to apply it to my business. Can anyone suggest any suggestions? Abbreviated source for my installed label:
<%= form_for(@label_set,
:html => { :onsubmit => "$('label_set_name').enable();" }) do |f| %>
<div class="field">
<%= label "label_sets", t('.label_set') %><br />
<%= select_tag("label_sets",
options_for_select(LabelSet::NAMES),
{ :include_blank => t('.new'),
:onchange => "if (this.value.empty()) {
$('label_set_name').clear();
$('label_set_name').enable();
} else {
$('label_set_name').value = this.value;
$('label_set_name').disable();
}" }) %><br />
</div>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% end %>
Refresh . I think I solved my problem or at least got a form view that looked cleaner by pulling out all the javascript and typing it in application.js(and writing it in jQuery just to try something new).
The appearance of the new form is as follows:
<%= form_for(@label_set) do |f| %>
<div class="field">
<%= label "label_sets", t('.label_set') %><br />
<%= select_tag("label_sets",
options_for_select(LabelSet::NAMES),
{ :include_blank => t('.new') }) %><br />
</div>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% end %>
The new one application.jslooks like this:
$(function() {
$('.new_label_set, .edit_label_set').submit(function() {
if ($('#label_set_name').attr('disabled') == true) {
$('#label_set_name').removeAttr('disabled');
}
});
$('#label_sets').change(function() {
if ($(this).val() == '') {
$('#label_set_name').val('');
$('#label_set_name').removeAttr('disabled');
} else {
$('#label_set_name').val($(this).val());
$('#label_set_name').attr('disabled', true);
}
});
});