Aaron Aaron - 8 months ago 44
Javascript Question

Getting the individual checkbox value in JQuery

I have several checkboxes and have a JQuery function that I want to print out the value I give each checkbox when I click on the checkbox. However, 1 keeps printing out. I assign each checkbox an item.id based on a primary key from my db using Rails. Here is my code

$('input[type="checkbox"]').on("change", function() {
var hall_id = $(this).val(); // here is where I want to get the value that I assigned to the checkbox
if (this.checked) {
console.log( hall_id );
} else {
console.log( hall_id );

<%= link_to "Logout", root_path %>

<h1>Hello <%= @user.first_name%> <%= @user.last_name%></h1>

<%= form_for @item do |f| %>
<%= f.label :to_do %>:
<%= f.text_field :to_do %><br />
<%= f.hidden_field :email, :value => @user.email%>

<%= f.submit %>
<% end %>

<% @items.each do |item|%>
<%if item.email == @user.email%>
<%= form_for @item do |f| %>
<%= item.id%>
<%= f.check_box :to_do, :value => item.id%> //This is where I assign the value for the check box
<%= item.to_do%><br />
<% end %>

enter image description here
In the image I am trying to print out the number by the checkbox(item.id), but in the console it only prints out 1

Answer Source

Look at the documentation on the check_box helper method: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box

Notice that the optional 4th argument is the checked_value which defaults to 1. Here is how you can switch it to the id of your item object:

<%= f.check_box :to_do, :id, {}, item.id %>