我需要设置隐藏 div 的值,使其等于按钮的值。我认为下面的代码是正确的方法,但是当我单击“编辑”按钮时,我没有看到 div 的值更新。
按钮
<td>
<button id="@user.UserId" class="updateUser" value="@user.UserId">Edit</button>
</td>
div
@Html.HiddenFor(m => m.User_Id, new { @class = "updateUserId" })
jQuery
<script type="text/javascript">
$(document).ready(function () {
var updateUserId = $('div.updateUserId').val();
$('button.updateUser').click(function () {
updateUserId = $('button.updateUser').val();
return updateUserId;
})
})
</script>
最佳答案
这里有两个问题;首先,Razor 的以下行将写入隐藏的 <input />
元素添加到您的文档(而不是 <div>
):
// Produces <input type="hidden" class="updateUserId" ... />
@Html.HiddenFor(m => m.User_Id, new { @class = "updateUserId" })
这意味着您需要更新脚本以选择元素作为 input
(而不是作为 div
)以更新其值。
第二个问题是您在单击事件期间将按钮值应用于隐藏输入的逻辑。实现您所需的一种方法是进行以下调整:
$(document).ready(function () {
$('button.updateUser').click(function (event) {
// Prevent possible form submission?
event.preventDefault()
// Obtain user value from this updateUser button
var updateUserValue = $(this).val();
// Select hidden input with class updateUserId and update
// the value to that of the button
$('input.updateUserId').val(updateUserValue);
});
});
希望有帮助!
关于JavaScript:如何将按钮元素的值分配给另一个div元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294512/