我在下面嵌套了表格,其中包含 div 元素和输入。我想在单击按钮时捕获并获取输入类型文本之一的值。显然现在,使用下面的 jquery 代码无法获取带有 class="name"的输入文本,但第一个输入和文本区域能够捕获。那么,当单击按钮时,使用 class =“name” 捕获第二个输入文本的值的确切代码是什么?谢谢,详细信息如下:
JQuery 代码:
$(function () {
$('.postrep').click(function () {
// e.preventDefault();
var inputs = $(this).closest('div').find('input'); //finding the inputs inside the div
var textin = $(this).closest('div').find('textarea'); //finding the textarea inside the div
var dataObject = {
Id: inputs.first().val(), // getting the first input value in the div
name: inputs.first('input').next('.name').val(), // How do I get this second input value?
reply: textin.first().val() //getting the value of the first textarea in the div
};
});
});
HTML:
<table id="mytable">
<tr >
<td class="tdstyle" >
<div style="font-weight:bold;"> @Html.DisplayFor(modelItem => item.name) </div>
<p> @Html.DisplayFor(modelItem => item.comment) </p>
<p > <input type="button" id="like" name="like" value="Like" /> <input type="button" class ="Reply" name="Reply" value="Replie(s)" /></p>
<div id="divReply" class ="divrep" >
<table>
<tr >
<td >
<div style="font-weight:bold;"> @Html.DisplayFor(modelItem => item2.name) </div>
<p> @Html.DisplayFor(modelItem => item2.reply) </p>
</td>
</tr>
</table>
<div>
<div class="editor-field" style="display:none; margin-bottom:5px;margin-top:5px">
<input type="text" id="comidvalue" name="id" class="id" value="@Html.DisplayFor(modelItem => item.Id)" />
</div>
<br />
<input type="text" id="namerep" name="name" class="name" /> <!-- I want to get the value of this -->
<br />
<textarea id="reply" name="reply" class="reply" ></textarea>
<br />
<input type="button" class="postrep" value="Post Reply" name="butname" style="cursor:pointer" />
</div>
<br />
</div>
</td>
</tr>
</table>
最佳答案
您可以使用id
选择器来获取输入框的值
$('#namerep').val();
但请确保您没有多个具有相同 id
的输入,如果您有多个 id
,则删除 id 并使用 class="name "
仅用于获取输入值。
您可以使用 jQuery 属性选择器通过 class="name"
获取输入值,请参阅下面的代码 -
$(function () {
$('.postrep').click(function () {
// e.preventDefault();
//store parent div in a variable and use it at multiple places
var $parentDiv = $(this).closest('div');
var inputs = $parentDiv.find('input'); //finding the inputs inside the div
var textin = $parentDiv.find('textarea'); //finding the textarea inside the div
var dataObject = {
Id: inputs.first().val(), // getting the first input value in the div
name: $parentDiv.find('input[class="name"]').val(), //get closest div and find input with class="name"
reply: textin.first().val() //getting the value of the first textarea in the div
};
});
});
关于javascript - 如何获取嵌套表的 div 内输入文本的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270490/