1

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.

jsFiddle

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');​​​​​
  }

}
Community
  • 1
  • 1
egr103
  • 3,858
  • 15
  • 68
  • 119

1 Answers1

4

$('#businessname').attr('required');​​​​​ retrieves the value of the attribute. To set it, you have to give a value to set: $('#businessname').attr('required', 'required');​​​​​

But for required and similar, it's better to use the reflected property instead. Reading: x = $('#businessname').prop('required');, writing: $('#businessname').prop('required', true); or $('#businessname').prop('required', false);.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875