Passing text in HTML element through link_to
I'm working on a page that displays a company structure (the index view of the Position class), which is an unordered list of positions.
When a position is clicked the text changes to white, and I want the name or id of that position to be passed to the controller when the "New Position" link is clicked.
I tried making it so that a hidden paragraph is set to contain the name of the selected position, but then I don't know how to access the paragraph within link_to.
Any suggestions? Here is the code:
<ul>
<% @positions.each do |position| %>
<% indent = "text-i开发者_JAVA技巧ndent:" + ((position.depth_level - 1) * 20).to_s + "px;" %>
<li style=<%=indent%> class="position_item"><%= position.name %></li>
<% end %>
</ul>
<p id="selected_position" class="hide"></p>
<%= link_to 'New Position', new_position_path %>
<script>
$("li").click(function () {
$("li").removeClass("hilite"),
$(this).addClass("hilite"),
$("#selected_position").text($(this).text());
});
</script>
If you're wanting it to be passed to the controller, you need to do so using a form (or you could also use a jQuery ajax()
call). Also, you should just use a hidden field to store the position value in temporarily since that's probably the more proper way of doing it.
<ul>
<% @positions.each do |position| %>
<% indent = "text-indent:" + ((position.depth_level - 1) * 20).to_s + "px;" %>
<li style=<%=indent%> class="position_item"><%= position.name %></li>
<% end %>
</ul>
<% form_tag(new_position_path, :id => "new_position", :method => "GET") do %>
<input name='selected_position' type='hidden' value='' />
<input name='commit' type='submit' value='New Position' />
<% end %>
<script>
$("li").click(function () {
$("li").removeClass("hilite"),
$(this).addClass("hilite"),
$("input[name='selected_position']").val($(this).text());
});
</script>
When the submit button is pressed, the selected_position
param will be passed along in the form and will be available in the controller as param[:selected_position]
Hope that helps!
精彩评论