【问题标题】:On select/unselect of checkboxes show the add/remove the values in textarea in rails在选择/取消选择复选框时显示添加/删除rails中textarea中的值
【发布时间】:2015-09-08 09:58:49
【问题描述】:

在我的 rails 应用程序中,记录列表显示在每条记录前面的复选框和一个用于选择所有记录的复选框。我想向文本区域添加或删除 parents_contact_no 数据。在选择复选框时,应将相应记录的 parents_contact_no 添加到以逗号分隔的文本区域,并在取消选择相应记录的复选框时,应删除相应记录的 parents_contact_no。 如果选中全选复选框,则所有记录的 parents_contact_no 应添加到文本区域。

需要显示数字的文本区域

  <div class="field">
    <%= f.label :sent_to %><br>
    <div class="result_div">
      <%= f.text_field :sent_to %>
    </div>
  </div>

.html.erb 文件

<% if @contact.empty? %>
    <h4>No records to display</h4>
<% else %>

    <table>
      <thead>
        <tr>
          <th><%= check_box_tag "contact_nos[]", @contact.map(&:parents_contact_no) %></th>
          <th>Roll no</th>
          <th>Class</th>
          <th>Section</th>

          <th>Father name</th>

          <th>Parents contact no</th>

          <th colspan="3"></th>
        </tr>
      </thead>

      <tbody>
        <% @contact.each do |student| %>
          <tr>
            <td><%= check_box_tag "contact_no[]", student.parents_contact_no %></td>
            <td><%= student.roll_no %></td>
            <td><%= student.class_name %></td>
            <td><%= student.section %></td>

            <td><%= student.father_name %></td>

            <td><%= student.parents_contact_no %></td>

            <td><%= link_to 'Show', student %></td>
            <td><%= link_to 'Edit', edit_student_path(student) %></td>
            <td><%= link_to 'Destroy', student, method: :delete, data: { confirm: 'Are you sure?' } %></td>
          </tr>
        <% end %>
      </tbody>
    </table>
<% end %>

如何通过 jquery/javascript 做到这一点?

我添加了一个脚本,该脚本在更改复选框时将添加/删除文本区域中的联系人。我面临的问题是如何获取当前复选框的值并将其放入文本区域。

<script>
  $(document).ready(function() {
    $('[id^=contact_no_]').change(function() {
        alert("checked");
        alert($('input["name=contact_no[]"]:checked').value());
        $('#message_message_text').val("Hello");

    });
  });
</script>

【问题讨论】:

    标签: javascript jquery html ruby-on-rails checkbox


    【解决方案1】:

    我得到了答案,对我有用的脚本如下

    <script>
      $(document).ready(function() {
        $('[id^=contact_no_]').change(function() {
            //alert("checked");
            var checkedValues = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get().join(", ");
            //alert(checkedValues);
            $('#message_sent_to').val(checkedValues);
    
        });
      });
    </script>
    

    解释:由于我们想要获取复选框的 id,该复选框的形式将是第一条记录的 contact_no_1 和第二条记录的 contact_no_2,依此类推。因此,我们使用正则表达式(如 id^=contact_no_)获取 id,并在此基础上调用了一个更改函数,该函数适用于选择和取消选择。比我们为所有被选中的复选框获取变量checkedValues中的值,并以逗号为基础加入值。最后,我们在 textarea 中添加了 checkeValues 变量内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      相关资源
      最近更新 更多