JQuery prop('required',false,(!$(this).is(':checked'))无效

时间:2016-04-21 16:20:39

标签: javascript jquery

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

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

检查时:

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

取消选中时:

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

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

$(':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/

1 个答案:

答案 0 :(得分:0)

正如@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')));
  }
});