在我的rails应用程序中,会显示一个记录列表,每个记录前面都有一个复选框,另一个复选框用于选择所有记录。我想在文本区域添加或删除parents_contact_no数据。在选择复选框时,相应记录的parent_contact_no应该被添加到用逗号分隔的文本区域,并且取消选择相应记录的复选框,相应记录的parents_contact_no应该被删除。 如果选中all all复选框,则所有记录的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>
答案 0 :(得分: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,并且我们调用了一个改变函数,它可以用于select和unselect。比我们在变量checkedValues中获取所有复选框的值,这些复选框被检查并根据逗号加入值。最后,我们将checkeValues变量内容添加到textarea。