rails form - 2 fields with same id in a form - how to disable second field when first field is selected
I have in my rails form the following code:
<label>Fruit: </label> <%= f.select(:IST_FRUIT, [['Apple', 'Apple'],
['Orange', 'Orange'],
['Kiwi', 'Kiwi'],
['Other', 'Other']
],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other')
{document.getElementById('otherTissue').style.display = 'block';
} "}
)开发者_Go百科 %>
<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :IST_FRUIT, :size => 10 %></span>
User can select a fruit form the listbox but if user selects 'Other', a textfield is diaplayed allowing user to input his value.
The problem is that when user selects a fruit and save the form, the fruit field in blank in the table and the reason is that the form is saving the second field 'IST_FRUIT' found in the span with id 'IST_FRUIT'.
I would be really grateful if someone could show me a way how to disable the second field when 'other' is not selected and enable it when 'Other' is selected from the dropdown list.
Many many thanks for any suggestion provided.
First, be aware that rails posts are based on fields' name, not ids.
In your case, you should use a virtual attribute
to store the potential other fruit
value.
Your model could look like:
attr_accessor :other_fruit
before_save :check_fruits
def check_fruits
#if other_fruit is not nil, it means that you want to store it's value in you IST_FRUIT column
#BTW, why these capital letters?
IST_FRUIT = other_fruit unless other_fruit.nil?
end
And your form would be:
<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :other_fruit, :size => 10 %></span>
I have another advice. Instead of disabling a HTML input (by the way - an ID must be unique in a HTML document) just make another attribute in your model, name it 'other_fruit' for example, and use this value if the 'fruit' is set to 'other' or is empty. For example you may write something like this:
class TheModel
attr :other_fruit
# Overwritten accessor for the fruit attribute.
# Returns the values of :other_fruit if :fruit is blank.
#
def fruit
if self[:fruit].blank?
other_fruit
else
self[:fruit]
end
end
end
Now the HTML part. In your JavaScript you set 'display' to block, but you do not reset it when user selects another option.
If you want to prevent the field from being sent to the server, you should set the 'disabled' attribute. Setting the 'style' only hides the control from the user's eyes.
精彩评论