jQuery移除hidden属性无效求助:.NET Core视图动态显示日期字段
问题解决方法
方案一:用容器包裹输入框(推荐)
先修改.NET Core视图代码,把FruitDate输入框放在容器内,通过控制容器的显示/隐藏实现需求,避免动态修改input类型的兼容性问题:
<div class="form-group"> <label asp-for="FruitsIncluded">*Fruits to be included</label><br/> <input type="radio" asp-for="FruitsIncluded" class="notification-option" value="ALL" /><b> All</b> <input type="radio" asp-for="FruitsIncluded" class="notification-option" value="Red" /><b> Red Fruits</b> <br/><br/> <div id="fruitDateContainer" @(Model.FruitsIncluded != "Red" ? "style='display: none;'" : "")> <input asp-for="FruitDate" class="form-control date-mask" /> </div> </div>
然后更新jQuery代码,操作容器的显示状态:
$(document).on("change", "input[type=radio][name=FruitsIncluded]", function() { const selectedValue = this.value; const $dateContainer = $("#fruitDateContainer"); const $dateInput = $("#FruitDate"); if (selectedValue === "Red") { $dateContainer.show(); } else { $dateContainer.hide(); $dateInput.val(""); // 清空输入值 } });
方案二:动态修改input类型(注意兼容性)
如果不想调整视图结构,也可以直接修改input的type属性,但需注意部分旧浏览器(如IE)不支持动态修改input类型:
$(document).on("change", "input[type=radio][name=FruitsIncluded]", function() { const selectedValue = this.value; const $dateInput = $("#FruitDate"); if (selectedValue === "Red") { $dateInput.attr("type", "text").show(); } else { $dateInput.attr("type", "hidden").val(""); } });
问题根源
之前代码失效的核心原因是:初始选中"ALL"时,FruitDate的type被设为hidden——浏览器对type="hidden"的输入框有特殊处理,即便调用show()修改display属性,也无法让它显示。必须将type改回text,或者通过容器控制显示才能生效。
内容的提问来源于stack exchange,提问作者TheFallenOne
相关产品推荐
相关产品推荐

