javascript - 循环中的表仅选择选中复选框的 td

标签 javascript html checkbox input

我试图做到这一点,以便当用户选择一个复选框然后点击一个按钮(下面的代码中未显示)时,他们将被重定向到一个新页面,其中包含某些详细信息。我需要为此获取 asset.id 值。我的问题是,我不确定从哪里开始获取这些值并使其与 submit 按钮一起使用。

HTML

<thead>
  <tr>
    <th>Select</th>
    <th>Model</th>
    <th>Asset Number</th>
    <th>Warranty</th>
    <th>Notes</th>
    <th>Actions</th>
 </tr>
</thead>
<tbody>

   {%  for asset in assets  %}
      <tr>
       <td><input type="checkbox"/></td>
       <td>{{asset.model}}</td>
       {% if loop.first %}<td class="tour-step tour-step-sixteen"><a href="/dashboard/it/asset/{{asset.id}}">{{ prefix }}{{asset.assetNumber}}</a></td>
       {% else %}
       <td><a href="/dashboard/it/asset/{{asset.id}}">{{ prefix }}{{asset.assetNumber}}</a></td>
       {% endif %}
        <td>{{asset.warranty | date("y-m-d")}}</td>
        <td>{{asset.notes}}</td>
        <td>
           <form id="label-form" action="/dashboard/it/label/print" method="POST">
            <button type="submit" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>
           </form>
         </td>
      </tr>
    {% endfor %}

 </tbody>

我还没有 JS,因为我不确定如何开始获取我需要的值以及如何将它们保存/传递到我的 POST 路由上。即使是指导也很棒。

我现在已经花了 3.5 个小时在网上查找,但我发现没有一个解决方案似乎是完整的,它们都缺少一些东西,或者是针对单个值而不是像我需要的多个值。

最佳答案

您可以循环表 tr 并获取那些选中了复选框的 id。

提交表单时,可以调用该函数,获取数组y并将该数组传入服务器。

这只是一个简单的示例,现在您可以随意使用代码

getSelected = function(){
  var array = [];
  $('#my_table tbody tr').each(function(index, object){
    if($(this).find('input[type="checkbox"]').prop("checked"))
      array.push($(this).find('.id').html());
  });
  console.log(array);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my_table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Value</th>
        <th></th>
      </tr>
    </thead>
		<tbody>
			<tr>
				<td class="id">1</td>
				<td>Hola</td>
				<td><input type="checkbox"></td>
			</tr>
			<tr>
				<td class="id">2</td>
				<td>Como</td>
				<td><input type="checkbox"></td>
			</tr>
			<tr>
				<td class="id">3</td>
				<td>Stas</td>
				<td><input type="checkbox"></td>
			</tr>
		</tbody>
	</table>
  <button onclick="getSelected()"> Get Selected </button>

关于javascript - 循环中的表仅选择选中复选框的 td,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48383731/

相关文章:

javascript - 如何将表单提交到页面,以便该新页面在新窗口(而不是新选项卡)中打开?

html - 超大屏幕背景图片没有响应

javascript - 当用户的 Javascript 关闭时,是否可以在网页上显示隐藏按钮?

excel - 我想确定以黄色突出显示的按钮的正确代码

javascript - 由于实现 $mdDialog( Material 设计),Angular 没有更新循环

javascript - 在表内显示 ajax 响应

javascript - CRUD 策略,每个 CRUD 操作使用一次还是两次调用?

javascript - 从页面顶部滚动 100px 后显示 div

javascript - 具有动态输入字段的动态表中的复选框

jsp - 使用 Servlets 和 JSP 从 html 表中获取选定的行