【问题标题】:JQuery prop('required', false, (!$(this).is(':checked')) not workingJQuery prop('required', false, (!$(this).is(':checked')) 不起作用
【发布时间】:2016-04-21 16:20:39
【问题描述】:

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

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

检查时:

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

取消选中时:

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

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

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

【问题讨论】:

  • 我不知道任何采用三个参数的.prop() 实现。
  • api.jquery.com/prop/#prop-propertyName-function 在这种情况下,它就像一个条件。
  • 是的,它仍然需要两个参数:属性名称和返回值的函数。
  • @PaulAbbott 好的,如果我删除 false 正在工作。

标签: javascript jquery


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 2020-04-28
    • 2020-02-08
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多