【问题标题】:Table in loop select only td where checkbox is selected循环中的表仅选择选中复选框的 td
【发布时间】:2018-01-22 14:23:35
【问题描述】:

我试图做到这一点,以便当用户选择一个复选框然后点击一个按钮(未在下面的代码中显示)时,他们将被重定向到其中包含某些详细信息的新页面。我需要为此获取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 个小时在网上寻找,但我发现没有一个解决方案似乎是完整的,它们都缺少一些东西,或者是单个值而不是我需要的多个值。

【问题讨论】:

标签: javascript html checkbox input


【解决方案1】:

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

提交表单时,您可以调用该函数,获取数组并将该数组发布到服务器。

这只是一个简单的例子,现在你可以随心所欲地玩代码

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>

【讨论】:

  • 我尝试完全添加您的代码,但它不起作用。我在页面顶部的脚本标记中有 HTML,然后是 JS。我也在页面底部尝试过。它告诉我该函数未在 Chrome 控制台中定义。
  • 我得到了它的工作排序,我该如何更改它而不是 innerhtml 它给我输入的名称?
  • 我不知道您使用的是什么类型的输入,但通常您使用 javascript 中的 .value 属性和 jquery 中的 .val() 获取输入值。
猜你喜欢
  • 2012-06-06
  • 2019-06-20
  • 2023-02-07
  • 1970-01-01
  • 2017-11-19
  • 2014-11-11
  • 2013-06-23
  • 1970-01-01
  • 2018-06-23
相关资源
最近更新 更多