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, %>

  <% 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>


So I tried to put (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,, value: %>

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_#{}" %>

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!


Now read this

cordova setup

sudo npm install -g ionic cordova sudo npm install -g ios-sim Cordova.js will be generated when you build a specific platform (i.e. cordova build android) ionic start cordovaApp tabs cd cordovaApp ionic platform add ios ionic build ios... Continue →