Javascript 不会对带有变量 id 的复选框做出反应以显示隐藏的文本框

Javascript do not react on checkbox with variable id to show hidden Textbox

本文关键字:显示 文本 隐藏 复选框 id 变量 Javascript      更新时间:2023-09-26

我在隐藏和显示基于复选框的文本框时遇到问题,因为它基于变量 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 开头的文本框的下一个元素。