AnthonyGalli.com AnthonyGalli.com - 6 months ago 12
jQuery Question

How to save attribute which is being overridden as nil?

The

ranking
only saves if the user saved it under the note that was first in chronological order.

enter image description here

challenges/show

<% @challenge.dates_challenged.first(@challenge.days_challenged + @challenge.missed_days).each_with_index do |date, i| %>
<% if @notes.any? { |note| note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") } %>
<% @notes.each do |note| %>
<% if note.notes_text.present? %>
<% if note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") %>
<div class="notes-notes-background">
<% if note.ranking == 1 %>
<%= image_tag '1.png', class: 'note-emoticon' %>
<% elsif note.ranking == 2 %>
<%= image_tag '2.png', class: 'note-emoticon' %>
<% elsif note.ranking == 3 %>
<%= image_tag '3.png', class: 'note-emoticon' %>
<% elsif note.ranking == 4 %>
<%= image_tag '4.png', class: 'note-emoticon' %>
<% end %>
<div style="font-weight: bold; font-size: 14px; color: #a0b4f0;">DAY <%= i + 1 %></div>
<b><%= note.notes_date.strftime("%b %d, %Y") %></b><br><br>
<div style="margin-left: 20px; margin-right: 20px;">
<%= link_to edit_note_path(note) do %>
<%= simple_format note.notes_text %>
<% end %>
</div>
</div>
<% end %>
<% else %>
<% end %>
<% end %>
<% else %>
<div class="notes-form-background" style="padding-top: 1em;">
<div style="margin-bottom: -19px; color: #a0b4f0; font-weight: bold; font-size: 14px; color: #a0b4f0;">DAY <%= i + 1 %></div><br>
<div style="color: #eee;"><%= date.strftime("%b %d, %Y") %></div>
<div style="margin-left: 20px; margin-right: 20px;">
<%= render 'notes/form', :date => date %>
</div>
</div>
<% end %>
<% end %>


notes/form

<%= form_for [@notable, @note] do |f| %>
<%= f.hidden_field(:ranking, id: 'ranking') %>
<%= image_tag('1.png', data: { ranking: 1 }, class: 'image-clicker') %>
<%= image_tag('2.png', data: { ranking: 2 }, class: 'image-clicker') %>
<%= image_tag('3.png', data: { ranking: 3 }, class: 'image-clicker') %>
<%= image_tag('4.png', data: { ranking: 4 }, class: 'image-clicker') %>
<% end %>

<script>
$('.image-clicker').click(function() {
$('#ranking').val($(this).data('ranking'));
$('.clicked').removeClass('clicked')
$(this).addClass('clicked');
});
</script>


Everything else from the note is being saved such as the
text
, just not the
ranking
.

Answer

You can only have ONE and only ONE html id with the same name on a page. In your case, all your hidden fields have the same id #ranking.

Your jQuery selector will pick the first. Which explains why you're facing the issue.

Just give your hidden field a class and inside your click function, search the children for the ranking hidden field.

Comments