表格中的多个提交按钮
Posted
技术标签:
【中文标题】表格中的多个提交按钮【英文标题】:multiple submit buttons in from table 【发布时间】:2021-08-11 13:41:47 【问题描述】:需要一些帮助和建议。我有一个包含在表格中的表单,并且在每一行上都有一个表单输入和一个提交按钮,我想要做的是从该行捕获用户输入并按下提交按钮。困扰我的一件事通常是捕获表单输入值,我们将传递输入标签中的 name
值并将其传递给后端,在我的情况下它是烧瓶,所以我会做类似 comment = request.form.get('comment_1')
的事情。有人可以帮我弄清楚如何知道单击了哪个按钮和输入名称值标签,以便从该行输入中检索该输入值吗?
我还有一个JSFiddle
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form metohd="POST">
<table class="table">
<thead>
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
<td><input class="form-control form-control-sm" type="text"placeholder="Comment" name="comment_1" id="comment_1"></td>
<td><button type="submit" name="button-1" value="button-1" class="btn btn-primary">Submit</button></td>
</tr>
<tr>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
<td><input class="form-control form-control-sm" type="text"placeholder="Comment" name="comment_2" id="comment_2"></td>
<td><button type="submit" name="button-2" value="button-2" class="btn btn-primary">Submit</button></td>
</tr>
<tr>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
<td><input class="form-control form-control-sm" type="text" placeholder="Comment" name="comment_3" id="comment_3"></td>
<td><button type="submit" name="button-3" value="button-3" class="btn btn-primary">Submit</button></td>
</tr>
</tbody>
</table>
</form>
【问题讨论】:
【参考方案1】:您可以使用document.activeElement
const myForm = document.forms['my-form']
myForm.onsubmit = e =>
e.preventDefault()
let el_TR = document.activeElement.closest('tr')
if (el_TR)
let inEl = el_TR.querySelector('input')
console.clear()
console.log('input _name:', inEl.name, ', _value:', inEl.value )
-<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<form metohd="POST" name="my-form">
<table class="table">
<thead>
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
<td><input class="form-control form-control-sm" type="text"placeholder="Comment" name="comment_1" ></td>
<td><button type="submit" class="btn btn-primary">Submit</button></td>
</tr>
<tr>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
<td><input class="form-control form-control-sm" type="text"placeholder="Comment" name="comment_2" ></td>
<td><button type="submit" class="btn btn-primary">Submit</button></td>
</tr>
<tr>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
<td><input class="form-control form-control-sm" type="text" placeholder="Comment" name="comment_3" ></td>
<td><button type="submit" class="btn btn-primary">Submit</button></td>
</tr>
</tbody>
</table>
</form>
【讨论】:
以上是关于表格中的多个提交按钮的主要内容,如果未能解决你的问题,请参考以下文章