Hi I am using jQuery with rails 3 to display or not the same div with different data for each iteration. This is my code:
<% @event.event_criterias.each do |event_criteria| %>
<p>
<table>
<% cont = 1 %>
<% form_for event_criteria do |f| %>
<%= f.hidden_field :event_id %>
<%= f.hidden_field :is_free %>
<%= f.hidden_field :is_exclusive %>
<tr>
<td width="150px">
<%= f.label :name, event_criteria.name%>
</td>
<td>
<%= f.text_field :name%>
</td>
<td><%= f.submit "Update name", :disable_with => 'Updating name...'%></td>
<td><%= link_to '[delete]', event_criteria, :confirm => 'Are you sure?', :method => :delete %></td>
<% if !event_criteria.is_free and !event_criteria.is_exclusive %>
<td>Show options <%= check_box_tag 'show_event_criteria_options'+cont.to_s, 'event_criteria_options'+cont.to_s, false, :class => 'check_buttons' %></td>
<% cont += 1 %>
<td> <%= link_to 'Create options', new_event_criteria_option_path(:event_criteria_id => event_criteria.id) %> </td>
<% end %>
</tr>
</table>
<div id="event_criteria_options"+<%= cont.to_s%> style="display: none;" >
<%= link_to 'Create option', new_event_criteria_option_path(:event_criteria_id => event_criteria.id) %>
<% if event_criteria.is_free == false and event_criteria.is_exclusive == false %>
<p>Options: </p>
<table>
<% event_criteria.event_criteria_option.order('value').each do |event_criteria_option| %>
<tr>
<td><%= link_to event_criteria_option.value, event_criteria_option_path(event_criteria_option) %></td>
<td><%= link_to '[delete]', event_criteria_option, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<% end %>
<% end %>
</div>
<% if !event_criteria.is_free && !event_criteria.is_exclusive && event_criteria.event_criteria_option.size == 0 %>
<p><i> No options defined! </i></p>
<% end %>
<% end %>
<% end %>
And my jQuery code:
$(document).ready(function(){
$(".check_buttons").click(function(){
var divname = this.name;
var divvalue = this.value;
if ($("#"+divname).attr("checked")){
$("#"+divvalue).show("slow");
}else{
$("#"+divvalue).hide("slow");
}
});
});
The problem is that only displays div id= event_criteria_option+<%=cont.to_s%> when I check the first checkbox. When i check toher checkboxes it doesn’t displays anything.
What is the mistake?
The following line
should be
Because you need the ‘cont.to_s’ inside the HTML id double quotes.
Also on a side note, you should know that ruby conditional “&&” is not the same as key work “and”. You might want to change that in the line that reads like:
Read more about that here.