简体   繁体   中英

JQuery prop('required', false, (!$(this).is(':checked')) not working

(I've already read some other questions about this but none used this method)

I have some hidden fields that their respective checkboxes shows when checked and I'd also like to make these fields required when I check the checkbox and the opposite when unchecking.

When checking:

  • Show the input and make it required.

When unchecking:

  • Clean the input value, remove the required attribute and hide it again.

This is what I'm trying but it's not working (the required part):

$(':checkbox').change(function(event) {
  $(this).parent('.item').find('.input').toggleClass('hide', (!$(this).is(':checked')));
  $(this).parent('.item').find('.input :checkbox').prop('checked', false, (!$(this).is(':checked')));
  $(this).parent('.item').find('.input input').not(':checkbox, .opt').prop('required', true, ($(this).is(':checked')));
  $(this).parent('.item').find('.input input').not(':checkbox').val('').not('.opt').prop('required', false, (!$(this).is(':checked')));
  if (this.id == 'price2') {
    $('.sub-rent .input').toggleClass('hide');
    $('.rent :checkbox').prop('checked', false, (!$(this).is(':checked')));
    $('.rent').toggleClass('hide', (!$(this).is(':checked')));
  }
});

The html structure divides in three groups:

  • A checkbox with a single hidden input
  • A checkbox with two hidden inputs
  • A checkbox with two checkboxes with two hidden inputs each (the first also with a checkbox).

I'm also looking for the oportunity to know how could I optimze the code as much as possible.

https://jsfiddle.net/j30v4z9k/

As @PaulAbbott said, prop() doesn't take three parameters, so:

$(':checkbox').change(function(event) {
  $(this).parent('.item').find('.input').toggleClass('hide', (!$(this).is(':checked')));
  $(this).parent('.item').find('.input :checkbox').prop('checked', false);
  $(this).parent('.item').find('.input input').not(':checkbox').val('').not(':checkbox, .opt').prop('required', ($(this).is(':checked')));
  if (this.id == 'price2') {
    $('.sub-rent .input').toggleClass('hide');
    $('.rent').toggleClass('hide', (!$(this).is(':checked')));
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM