【问题标题】:Getting the individual checkbox value in JQuery在 JQuery 中获取单个复选框值
【发布时间】:2016-11-22 23:47:13
【问题描述】:

我有几个复选框,并且有一个 JQuery 函数,当我单击复选框时,我想打印出我给每个复选框的值。但是,1 一直打印出来。我使用 Rails 根据我的数据库中的主键为每个复选框分配一个 item.id。这是我的代码

<script>
$(document).ready(function(){
    $('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 );
    }
});
});
</script>



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

在图像中,我试图通过复选框(item.id)打印出数字,但在控制台中它只打印出 1

【问题讨论】:

  • 同时显示生成的 HTML 代码的样子。

标签: javascript jquery ruby-on-rails checkbox


【解决方案1】:

查看有关check_box 辅助方法的文档:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box

请注意,可选的第四个参数是checked_value,默认为1。以下是如何将其切换到 item 对象的 id

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

【讨论】:

    猜你喜欢
    • 2011-02-19
    • 1970-01-01
    • 2015-04-11
    • 2018-09-17
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    相关资源
    最近更新 更多