在my rails应用程序中,会显示一个记录列表,每个记录前面都有复选框,还有一个复选框用于选择所有记录。我想在文本区域中添加或删除家长联系人没有数据。在选中相应记录的父联系人号码的复选框时,应将其添加到以逗号分隔的文本区域;在取消选中相应记录的复选框时,应删除相应记录的父联系人号码。
如果选中“全选”复选框,则所有记录中的“家长联系人”都不应添加到文本区域。
必须在其中显示数字的文本区域
<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>
最佳答案
我得到了答案,对我有用的剧本如下
<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代表第二条记录,依此类推。所以我们得到了一个带有regex表达式的id,比如id^=contact_no,在这个函数中,我们调用了一个change函数,它将用于select和unselect。然后,我们在变量checkedValues中为所有选中的复选框取值,并在逗号的基础上连接这些值。最后,我们将checkeValues变量内容添加到文本区域。
关于javascript - 在选择/取消选中复选框时,显示添加/删除栏的textarea中的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30988612/