使用输入循环html表以获取值

  • 本文关键字:获取 html 循环 html jquery
  • 更新时间 :
  • 英文 :


我有一个看起来像的表

<table id="tableScanItems" class="table">
<th>Scan Item</th>
<th>Inactive</th>
<tr>
<td><input type='text' id='input1' class='form-control'/></td>
<td><input type='checkbox' id='checkbox1' class='form-control'/></td>
</tr>
<tr>
<td><input type='text' id='input2' class='form-control'/></td>
<td><input type='checkbox' id='checkbox2' class='form-control'/></td>
</tr>
<tr>
<td><input type='text' id='input3' class='form-control'/></td>
<td><input type='checkbox' id='checkbox3' class='form-control'/></td>
</tr>
</table>

单击一个按钮,我就可以运行这个jQuery。

$("#tableScanItems tr").each(function (){
$(this).closest('tr').find("input").each(function() {
...get the values for each row and do stuff
});
});

我需要循环html表来获得inputtype=text和inputtype=checkbox 的值

JS确实进行了正确的循环,并获得了inputtype=文本值,但没有获得inputtype=复选框值。我需要在.each中指定不同的参数来查看复选框的值吗?

Ryan

编辑如果执行此操作,我将看不到用户输入的值。

$(this).closest('tr').find("input").each(function() {
alert(this.value)
});

您可以像下面这样循环。你需要以不同的方式对待复选框才能获得它们的值:

$("#tableScanItems tr").each(function (){
$(this).closest('tr').find("input").each(function() {
var elem = $(this);
if (elem.is(':checkbox')) {
console.log( !!elem.attr("checked"));
} else {
console.log(elem.val());
}
});
});

在这里工作小提琴:https://jsfiddle.net/5yt9hon1/1/

选中一些复选框并点击提交。您将在div中看到复选框的值。

$(document).ready(function () {
$('#btnSubmit').click(function () {               
var result = $('input[type="checkbox"]:checked') 
if (result.length > 0) {
var resultString = result.length + " checked <br/><br/>"
result.each(function () {
resultString+= $(this).val() + "<br/>";
});
$('#divCheckboxValues').html(resultString);
}
else {
$('#divCheckboxValues').html(" No checkbox checked");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id="tableScanItems" class="table">
<th>Scan Item</th>
<th>Inactive</th>
<tr>
<td><input type='text' id='input1' class='form-control'/></td>
<td><input type='checkbox' id='checkbox1' class='form-control'/></td>
</tr>
<tr>
<td><input type='text' id='input2' class='form-control'/></td>
<td><input type='checkbox' id='checkbox2' class='form-control'/></td>
</tr>
<tr>
<td><input type='text' id='input3' class='form-control'/></td>
<td><input type='checkbox' id='checkbox3' class='form-control'/></td>
</tr>
</table>
<input id="btnSubmit" type="submit" value="submit" />
<br />
<div id="divCheckboxValues">
</div>

最新更新