I have two radio buttons, "Yes", and "No", and one text field. If a user clicks on "Yes", then the disabled text field is enabled and required. I would like the text field border to be red when required, and have created a class to do this. I have also created a class to make the the text field gray to be used after the field is populated. My question is in how to correctly apply the required class and then apply the validated class on the text field.
The solution I have below involves adding a function in the blur method, which seems to work. The issue is that if I then decide to click "No" and then click back on "Yes", the red border doesn’t show.
Any suggestions on how to solve this or how to optimize my code would be greatly appreciated. Thank you!
HTML
<input class="form-check-input radio" type="radio" name="radio" id="Yes" value="Yes" />
<label class="radio" for="Yes">Yes</label>
<input class="form-check-input radio" type="radio" name="radio" id="No" value="No" />
<label class="radio" for="No">No</label>
<br />
<label for="required_later">Enable if "Yes"</label>
<input type="text" name="textfield" id="textfield" placeholder="required" disabled>
CSS
.req {
border: 1px solid red;
}
.valid {
border: 1px solid #ced4da;
}
Jquery
$("#Yes").click(function() {
$("#textfield").prop("required", true).addClass("req");
$("#textfield").prop("disabled", false);
$("#textfield").blur(function () {
$("#textfield").addClass("valid");
});
});
$("#No").click(function() {
$("#textfield").prop("required", false).removeClass("req").val("");
$("#textfield").prop("disabled", true);
});
Here is the JSFiddle: https://jsfiddle.net/L4529nzx/1/
2
Answers
I made it simpler
The required and valid were clashing
Looks like it works better now
this is what i came up with.