I've seen this thread already: Add required attribute when radio is checked however, the answers do not target the ID of the specific radio button, only the name. I cannot acheive what I want using the name approach as the names need to be the same for my radio options, please see HTML to see what I mean.
The below code shows a radio button with just two options. It reveals the #ifYes div ONLY when the radio option #yesCheck is checked. It gets hidden if #noCheck is checked.
My problem
At the same time #ifYes
is revealed I want to add the required attribute to the 2 inputs within #ifYes
(#businessname and #regnum
). required
attribute to also be removed when #ifYes
is hidden.
HTML
<label>Are you a business or consumer?</label>
<span>Business</span><input type="radio" onclick="javascript:yesnoCheck();" value="Business" name="customer[note][Business or Consumer?]" id="yesCheck" required/><br/>
<span>Consumer</span><input type="radio" onclick="javascript:yesnoCheck();" value="Consumer" name="customer[note][Business or Consumer?]" id="noCheck" /><br/>
<div id="ifYes">
<label for="businessname">Business name</label>
<input id="businessname" type="text" name="customer[note][Business Name]" placeholder="Business Name" />
<label for="regnum">Business Registration No.</label>
<input id="regnum" type="text" name="customer[note][Business Reg No.]" placeholder="Business Registration No." />
</div>
JS
function yesnoCheck() {
if($('#yesCheck').is(':checked')) {
$('#ifYes').addClass('yarp');
$('#businessname').attr('required');
} else {
$('#ifYes').removeClass('yarp');
$('#businessname').removeAttr('required');
}
}