JQuery prop('required', false, (!$(this).is(':checked')) 不起作

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

本文关键字:is checked required prop false JQuery this      更新时间:2023-09-26

(我已经读过一些关于这个问题的其他问题,但没有一个使用这种方法)

我有一些隐藏的字段,它们各自的复选框在选中时会显示,我还想在选中复选框时使这些字段成为必需字段,而在取消选中时则相反。

检查时:

  • 显示输入并使其成为必需的。

取消选中时:

  • 清理输入值,删除所需的属性并再次隐藏它。

这就是我正在尝试的,但它不起作用(必需的部分):

$(':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')));
  }
});

html 结构分为三组:

  • 具有单个隐藏输入的复选框
  • 具有两个隐藏输入的复选框
  • 一个复选框
  • ,其中包含两个复选框,每个复选框有两个隐藏输入(第一个也带有一个复选框)。

我也在寻找机会,以了解如何尽可能优化代码。

https://jsfiddle.net/j30v4z9k/

正如@PaulAbbott所说,prop()不需要三个参数,所以:

$(':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')));
  }
});