gpt4 book ai didi

javascript - 获取表 td 中的输入值

转载 作者:行者123 更新时间:2023-12-03 07:25:56 24 4
gpt4 key购买 nike

我有一个带按钮的表格,如下所示;我正在尝试使用 jQuery 获取 td 的值。

我的 table :

<table class="table" id="Tablesample">

<tr>
<th style="display:none;">
@Html.DisplayNameFor(model => model.Id)
</th>

</tr>

@foreach (var item in Model)
{
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="@item.Key" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="@item.Id" class="form-control" id="configId" readonly="readonly">
</td>
</tr>

}

</table>

<button id="btnSave">Save</button>

然后我尝试使用 jquery 获取值:
$('#btnSave').click(function () {

$('#Tablesample tr').each(function () {

var row = $(this).closest("tr"); // Find the row
var text = row.find(".keyvalue").text(); // Find the text
var keval = text.find("input").text();

alert(keval);
});

});

但我没有得到任何值(value)。

我也尝试过这样的事情,但它也不起作用:
$("#Tablesample tr:gt(0)").each(function () {

var this_row = $(this);
var key = $.trim(this_row.find('td:eq(0)').html());
alert(key);
});

最佳答案

问题是由于您的 DOM 遍历逻辑。首先thistr元素,所以 closest('tr')不会找到任何东西。其次,您从 text() 获取字符串值。的 .keyvalue ,然后尝试查找 input文本中的元素,而不是遍历 DOM。最后,你需要使用val()获取输入的值。

我强烈建议您熟悉 jQuery 公开的方法及其工作原理:http://api.jquery.com

尽管如此,这应该对你有用:

$('#btnSave').click(function() {
$('#Tablesample tr').each(function() {
var keval = $(this).find(".keyvalue input").val();
console.log(keval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="Tablesample">
<tr>
<th style="display:none;">
Model
</th>
</tr>
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="Key1" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="Id1" class="form-control" id="configId" readonly="readonly">
</td>
</tr>
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="Key2" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="Id2" class="form-control" id="configId" readonly="readonly">
</td>
</tr>
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="Key3" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="Id3" class="form-control" id="configId" readonly="readonly">
</td>
</tr>
</table>

<button id="btnSave">Save</button>


请注意,第一个值为 undefined作为您的 th第一行中的元素不包含 input元素。我建议使用 thead 分隔表格/ tbody如果您想排除该行。

关于javascript - 获取表 td 中的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41871848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com