Javascript 不会对带有变量 id 的复选框做出反应以显示隐藏的文本框
Javascript do not react on checkbox with variable id to show hidden Textbox
我在隐藏和显示基于复选框的文本框时遇到问题,因为它基于变量 ID。
我知道 markActiveLink2(el) 函数没问题,因为我可以在 Chrome 中的控制台中找到所选复选框和文本框的值。因此,例如,如果我选择第一个复选框,则值为CloseDateCheck0。但不知何故,我的javascript的第二部分不起作用。
提前感谢您的帮助。
JavaScript
//Hide and Show Close Date
//Set Variables
var CloseDateCheck_id = '';
var CloseDate_id = '';
//Define Variables, so it is known which Date i want to change
function markActiveLink2(el) {
CloseDateCheck_id = $(el).attr("id");
CloseDate_id = CloseDateCheck_id.replace("CloseDateCheck", "CloseDate");
}
//Hide and show Date based on the variable ids
$(document).ready(function(){
$("#"+ CloseDateCheck_id).click(function () {
//var $this = $(this);
if (this.checked) {
$("#"+CloseDate_id).show();
} else {
$("#"+CloseDate_id).hide();
document.getElementById(CloseDate_id).value = null;
}
});
});
.cshtml
@for (int i = 0; i < Model.OpenIssue.Count(); i++)
{
@*...*@
<b>Close Issue</b>
@Html.CheckBox("Finish", new { id= "CloseDateCheck"+i, onmousedown="markActiveLink2(this);"})
@Html.TextBoxFor(modelItem => modelItem.OpenIssue[i].CloseDate, "{0:dd.MM.yyyy}", new { @class = "datetype", type = "text", style = "width: 90px; display:none", id="CloseDate"+i })
@*...*@
}
已处理的网页
<b>Close Issue</b>
<input id="CloseDateCheck0" name="Finish" onmousedown="markActiveLink2(this);" type="checkbox" value="true">
<input name="Finish" type="hidden" value="false">
<input class="datetype hasDatepicker" data-val="true" data-val-date="The field CloseDate must be a date." id="CloseDate0" name="OpenIssue[0].CloseDate" style="width: 90px; display:none" type="text" value="">
溶液:
将 JavaScript 更改为:
$(document).ready(function(){
$('[id ^= "CloseDateCheck"]').change(function () {
if (this.checked) {
$("#"+CloseDate_id).show();
} else {
$("#"+CloseDate_id).hide();
document.getElementById(CloseDate_id).value = null;
}
});
});
您不会将 click
事件添加到文档 ready 上的任何元素,因为CloseDateCheck_Id
''
.
尝试这样的事情:-
$(document).ready(function() {
$('[id^="CloseDateCheck"]').change(function() {
var textbox = $(this).next('[id^="CloseDate"]');
if (this.checked) {
textbox.show();
} else {
textbox.hide();
textbox.val(null);
}
});
});
这会将 change
事件添加到 id 以 CloseDateCheck
开头的所有元素,然后查找 id 以 CloseDate
开头的文本框的下一个元素。
相关文章:
- xmlhttp.responseText不显示文本
- 如何在MVC中使用jQuery在文本框旁边显示文本
- 根据页面的位置突出显示文本中的字符
- 当选择值x时,Javascript需要在正确的位置显示文本区域,从而循环通过具有选择选项的表单
- 操作javascript变量[HTML]以只显示文本
- 如何显示文本长度,即使它超过ng最大长度
- 如何在悬停时显示文本而不移动页面上的内容
- ASP.NET MVC,在文本框旁边显示文本
- 可单击滚动图像以显示文本框
- 使用鼠标悬停JavaScript/HTML显示文本
- 延迟高亮显示文本区域中的文本
- 选择“选择选项”时显示文本.怎么做
- 无法使用JavaScript在画布上显示文本
- 在不更改HTML源代码的情况下,在管理员TinyMCE编辑器中突出显示文本
- 将鼠标悬停在图像上时显示文本
- javascript:在for循环中使用settimeout来定期显示文本
- 一页主题搜索/用下一个按钮突出显示文本
- JavaScript 在更改选择时不显示文本区域
- 用于突出显示文本的JQuery/JavaScript插件
- 模式显示文本区域内容不是字符串