I'm trying to toggle the required
attribute on fields using jQuery. On page load I add the required
attribute to the relevant elements:
$("[data-required]").attr("required", "");
Then I have a toggle function that does a number of things, including toggling the required
attribute:
if ($(childInput).attr('data-required')) {
if (element.checked) {
$(childInput).attr('required', '');
$(childInput).rules('add', { required: true });
}
if (!element.checked) {
$(childInput).attr('required', false);
$(childInput).rules('remove');
}
}
However, in both cases (on page load and on toggle), the required
attribute is being set to required="required"
. Am I using the incorrect syntax, or missing something here? I can't figure out why "required" would be inserted into the attribute value.
.attr("required", true);
and .attr("required", "true");
are resulting in the same behaviour.
OK, I'm not entirely sure why, but this works:
$("[data-required]").prop("required", true);
The if statement in the toggle function:
if ($(childInput).attr('data-required')) {
if (element.checked) {
$(childInput).prop('required', true);
$(childInput).rules('add', { required: true });
}
if (!element.checked) {
$(childInput).attr('required', false);
$(childInput).rules('remove');
}
}