I have a form that works, but I need to have some fields hidden unless the user clicks a link. Once they are exposed, everything is good. Here is t开发者_开发技巧he partial responsible for the form:
<%= fields_for :city do |builder| %>
<p class="fields>
<%= builder.label :name, "City" %>
<%= builder.hidden_field :name %><br />
<%= builder.label :state, "State" %>
<%= builder.text_field :state %>
<%= link_to_function "new city", "show_fields('city_name')" %>
</p>
<% end %>
Then in application.js
function show_fields(link) {
$(link).previous("input[type=hidden]").show;
}
When I try to run that and inspect it in chrome, I see the following error:
application.js4:Uncaught TypeError:Object# has no method 'previous'
Now, I admit I am totally new to js and still pretty new to ruby and rails, but I am pretty sure I am doing exactly what Ryan Bates did in one of the railscasts. (I have tried the show_fields(this) format too with the same result).
What is the correct way to target my hidden_field with a link that exposes it? This seems so simple, but I can't figure out why the previous method doesn't work. Sorry if this is obvious, but I seriously can't find the right place to start.
From what I can tell, the show method (or whatever it is called in JS) is not available for the fields that are created by the hidden_field helper. I got the idea to add a function to hide an existing text field and then use the show method on it and that worked just fine.
My solution then was to switch to jQuery and use:
$(document).ready(function() {
// hides the div as soon as the DOM is ready
$('div.newcity').hide();
});
to hide the div before the page is displayed to the user. Then I can easily show that div using:
function toggle_fields(link) {
$(link).toggle();
$(link).prev().toggle();
}
in application.js and:
<%= link_to_function "new city", "toggle_fields('div.newcity')" %>
in the view. I had to use the jquery-rails gem to get all of this working if anyone happens to stumble on this later.
精彩评论