form_for checkbox associated with label

I put a form with checkbox, submit button, and label in iteration block. And I wanted each label clickable.

<%= @tasks.each do |task| %>

  <%= form_for task, remote: true do |f| %>

    <%= f.check_box :complete %>
    <%= f.submit "update" %>
    <%= f.label :complete, task.name %>

  <% end %>

<% end %>

But clicking any label only ticked the first checkbox on the list.

First, for a clickable label in HTML, attribute name of label tag should match id name of input tag.

stackoverflow “How to create an HTML checkbox with a clickable label”

<label><input type="checkbox" name="checkbox" value="value">Text</label>

or should be

<input type="checkbox" name="checkbox" id="checkbox_id" value="value">
<label for="checkbox_id">Text</label>

Next, html.erb code above renders HTML with all the same id and for for each line.

<form accept-charset="UTF-8" action="/tasks/1" class="edit_task" data-remote="true" id="edit_task_1" method="post"><div style="display:none"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="patch"></div>

  <input name="task[complete]" type="hidden" value="0"><input checked="checked" id="task_complete" name="task[complete]" type="checkbox" value="1">  
  <label for="task_complete">Task Name</label>

</form>

So I tried to put task.id (which is given different for each task, each form) into the name of those tag attributes. I made input tag with value attribute on f.label helper.

  <%= f.label :complete, task.name, value: task.id %>

and it made HTML like,

<label for="task_complete_2">Task Name</label>

And I tried to do the same thing into <input id="task_complete"> (which was rendered by <%= f.check_box :complete %>). Somehow I figured this out:

<%= f.check_box :complete, id: "task_complete_#{task.id}" %>

And it made it like

<input checked="checked" id="task_complete_2" name="task[complete]" type="checkbox" value="1">

Now I have it as I wished. Clicking each label ticks same line checkbox. Yay!

 
10
Kudos
 
10
Kudos

Now read this

install zsh ubuntu 14.04 LTS

What I did is… open ubuntu software center and install “Shell with lots of features” (the first one on top when search by “zsh”) then did this (alternate way to install zsh) and, got “don’t have to” message. $ sudo apt-get update... Continue →