I have a check box on my web page with two radio buttons underneath it and two text boxes. The screen shot is below:
below is my code for checkbox. I want two radio button and two text boxes to be required if the checkbox is checked.
3. <input id="employ" asp-for="Employments.Sec3Employed" type="checkbox" />
This is the test for employment agency.
I have a class name called "OutEmploy" for each radio button and each input box like this:
<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>
Below is the Jquery function that I am running in order to make radio buttons and text box to be required:
$(function() {
$('#employ').on('click', function() {
if ($(this).is(':checked')) {
$('.outEmploy').attr('required', 'required');
} else {
$('.outEmploy').removeAttr('required');
}
});
});
when I click on the check box, the radio button and two text boxes should be required. Right now, when I click on the check box, two text boxes become required, but the radio button does not become required. Not sure, what am I doing wrong.
Any help is appreciated. This is how the error message looks like:
2
Answers
You can add a separate class or ID to the radio buttons and target them separately in your jQuery
For example, you could add a class outEmployRadio to the radio buttons and modify your jQuery function as follows:
Here added class outEmployRadio to the radio buttons and modified the jQuery function to target them separately using the class selector .outEmployRadio. Also used the .prop() method instead of the .attr() method to set the required property of the radio buttons to true or false.
Note, also added the class outEmployText to the text boxes to make sure only they become required when the checkbox is checked.
Your code result:
If you want more validation like text-danger you can add
asp-validation-for
like below :and add like :
result: