jlittlejohn
3/25/2014 - 8:21 PM

JS: Toggle Required Attribute based on Checkbox

JS: Toggle Required Attribute based on Checkbox

// Toggle Required Attributed based on Checkbox
(function(){
  var checkBox = $('input#acceptTextMessages');
  var input = $('input#cellPhoneNumber');

  function addRequired () {
    $(input).attr({required: true}).after('<span class="required">*</span>');
  }

  function removeRequired () {
    $(input).attr({required: false});
    $(input).next().remove();
  }

  function toggleRequired () {
    if ( $(this).is(':checked') ) {
      addRequired();
    } else {
      removeRequired();
    }
  }

  $(checkBox).on( 'click', toggleRequired );
})();