You are viewing limited content. For full access, please sign in.

Discussion

Discussion

Dynamically setting required on a field based on a radio button

posted on May 20, 2020

I am trying to set a field to change the Employee ID field (.empID) to not be required if the radio button "New Hire" is selected on the Requested Action field (.action).  I have that working, but when I select a different radio button the Employee ID field stays not required.  I would want it to change back to required whenever "New Hire" is not selected on the Required Action field.  Can someone please help me with the JavaScript I have?

$(document).ready(function() {
   
  /* This sets the Employee ID field to required using javascript */
  $('.empID label').append('<span class="cf-required">*</span>');
  $('.empID input').attr('required','True');
  

  /* This removes the required class and asterisk from the Employee ID field
     when the New Hire is selected, allowing the form to submit */
  $('.action input').change(function () {
        if ($('.action input[value="New Hire"]:checked').length > 0) 
    		$('.empID span.cf-required').remove();
            $('.empID input').removeClass('required').removeAttr('required');
  });
});

 

0 0
replied on May 20, 2020

Your current script is running when the "New Hire" button is checked, but you need another listener on the other radio option(s) available. If another option is checked, you'll want to add the "required" class and attribute to the employee ID field. 

Also instead of removing the required span when the "New Hire" button is checked, you can change the display to hidden, and then set the display to show when another option is selected.

1 0
replied on May 21, 2020

Thank you Julia.  I was able to achieve what I wanted with the following code.

$(document).ready(function() {

   $('.empID label').append('<span class="cf-required">*</span>');
   $('.empID input').attr('required','True');
  
  
  /* This removes the required class and asterisk from the Employee ID field
     when the New Hire is selected, allowing the form to submit */
  $('.action input').change(function () {
         if ($('.action input[value="New Hire"]:checked').length > 0){
    		$('.empID span.cf-required').remove();
            $('.empID input').removeClass('required').removeAttr('required');
   /* This adds the required class and asterisk from the Employee ID field
     when the other actions are selected.*/
  	  }  else  {
            $('.empID span.cf-required').remove();
    		$('.empID label').append('<span class="cf-required">*</span>');
  			$('.empID input').attr('required','True');
	  }
  });
});

 

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.