我的网页上有一个复选框,下面有两个单选按钮和两个文本框。截图如下:
下面是我的复选框代码。如果选中复选框,我需要两个单选按钮和两个文本框。
3. <input id="employ" asp-for="Employments.Sec3Employed" type="checkbox" />
这是职业介绍所的测试。
我为每个单选按钮和每个输入框都有一个名为“OutEmploy”的类名,如下所示:
<form asp-action="Create">
3. <input id="employ" asp-for="Employments.Sec3Employed" type="checkbox" />
<div class="col-sm-2">
@foreach (var rep in Model.Employments.reported) {
<input class="outEmploy"
type="radio"
asp-for="Employments.Reported"
value="@rep" />
@rep
<span style="margin-right:5px"></span> }
</div>
<div class="form-group row">
<div class="col">
<input asp-for="Employments.PositionTitle" class="outEmploy form-control " />
</div>
</div>
<div class="form-group row">
<div class="col">
<input asp-for="Employments.PositionTitle" class="outEmploy form-control" />
</div>
</div>
<input type="submit" id="myBtn1" value="Submit" />
</form>
下面是我运行的 Jquery 函数,目的是使单选按钮和文本框成为必需的:
$(function() {
$('#employ').on('click', function() {
if ($(this).is(':checked')) {
$('.outEmploy').attr('required', 'required');
} else {
$('.outEmploy').removeAttr('required');
}
});
});
当我点击复选框时,应该需要单选按钮和两个文本框。现在,当我单击复选框时,需要两个文本框,但不需要单选按钮。不确定,我做错了什么。
任何帮助表示赞赏。
您可以向单选按钮添加一个单独的类或 ID,并在您的 jQuery 中单独定位它们
例如,您可以将类 outEmployRadio 添加到单选按钮并修改您的 jQuery 函数,如下所示:
$(function(){
$('#employ').on('click', function () {
if ($(this).is(':checked')) {
$('.outEmployText').attr('required', 'required');
$('.outEmployRadio').prop('required', true);
} else {
$('.outEmployText').removeAttr('required');
$('.outEmployRadio').prop('required', false);
}
});
});
此处向单选按钮添加类 outEmployRadio 并修改 jQuery 函数以使用类选择器 .outEmployRadio 单独定位它们。还使用 .prop() 方法而不是 .attr() 方法将单选按钮的必需属性设置为 true 或 false。
注意,还将类 outEmployText 添加到文本框,以确保只有在选中复选框时才需要它们。
您的代码结果:
如果你想要更多的验证,比如文本危险,你可以像下面这样添加
asp-validation-for
:
<span asp-validation-for="Employments.Reported" class="text-danger"></span>
并添加:
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script>
$(function () {
$('#employ').on('click', function () {
if ($(this).is(':checked')) {
$('.outEmploy').attr('required', 'required');
} else {
$('.outEmploy').removeAttr('required');
}
});
});
</script>
}
结果: