lundi 29 août 2016

Checkbox Change event to trigger another field to be required

I have a form with several checkbox fields and a corresponding Comments fields for each checkbox. I dynamically create these fields. For example, the checkbox field, tag1, would correspond to comments1. When the checkbox is checked, I don't want to require comments. When it is not checked, I want to require comments.

Sometimes the fields are pre-populated based on a user's last input. In other words, the checkbox may already be checked when the page loads or it may not be. I have logic set to build the corresponding comments field as required or not required based on this.

Everything situation seems to be working except one. When I check the box and then uncheck the box, the form allows me to submit with no comments. Below is what I have tried.

$(document).on('change', 'input[type=checkbox]', function() {
  var checkbox = $(this),
    otherInput = $('#comments' + this.id.replace('tag', ''));


  otherInput.removeProp('required', !checkbox.is(':checked'));
  if (!checkbox.not(':checked')){
    otherInput.prop('required',true);
  }
});

--------------------second attempt

$(document).on('change', 'input[type=checkbox]', function() {
  var checkbox = $(this),
    otherInput = $('#comments' + this.id.replace('tag', ''));

  otherInput.prop('required', !checkbox.not(':checked'));
  otherInput.removeProp('required', !checkbox.is(':checked'));

});

Both of these solve the same situations, except the one noted above. Please advise.




Aucun commentaire:

Enregistrer un commentaire