Adam Adam - 5 months ago 31
Javascript Question

Jquery attr not working for required but will for title

I'm having a problem with attr while using the following:

$("input[name='choice']").change(function() {
if($('#opt_2').is(':checked')) {
$('#email').attr('required', true);
$('#reasonreport').attr('required', true);
} else {
$('#email').removeAttr('required');
$('#reasonreport').removeAttr('required');
}
if($('#ch7').is(':checked')) {
$('#reasonreport').attr('required', true);
} else {
$('#reasonreport').removeAttr('required');
}


});

email is an email input field



resonreport is a textarea input



When opt_2 is checked from a radio box it changed the email field to required but wont change the reasonreport textarea to required. The following works fine:

$('#reasonreport').attr('title', 'something');


Will add a title, but its just the required attr that wont set, ive been scratching my head for a while now and cant for the life of me work out why.

Any help is much appreciated. Thanks!

Answer

Fundamentally what you're doing should be working, because boolean attributes are "true" when they're present at all (regardless of value) and "false" when they're absent. But then, jQuery's attr (still) blurs the lines between attributes and properties and is not the right choice when trying to handle properties: Use prop with true to enable and false to disable the property. This also lets you markedly simplify the code:

$("input[name='choice']").change(function() {
    $('#email, #reasonreport').prop('required', $('#opt_2').is(':checked'));
    $('#reasonreport').prop('required', $('#ch7').is(':checked'));
});

...but note that you also have a logic error: You're setting the required property of #reasonreport based on opt_2's checked status, but then overwriting that based on ch7's checked status. You may as well completely remove the code setting #reasonreport's required in the opt_2 stuff; it ends up doing nothing.

If your goal is to require #reasonreport if both opt_2 and ch7 are checked, you'll need to modify the code.

$("input[name='choice']").change(function() {
    var opt_2_checked = $('#opt_2').is(':checked');
    var ch7_checked = $('#ch7').is(':checked');
    $('#email').prop('required', opt_2_checked);
    $('#reasonreport').prop('required', opt_2_checked && ch7_checked);
});

Or use || instead of && if the goal is to require it if either of them is checked.