【发布时间】: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结构分为三组:
- 带有单个隐藏输入的复选框
- 带有两个隐藏输入的复选框
- 一个带有两个复选框的复选框,每个复选框带有两个隐藏输入(第一个也带有一个复选框)。
我也在寻找机会了解如何尽可能优化代码。
【问题讨论】:
-
我不知道任何采用三个参数的
.prop()实现。 -
api.jquery.com/prop/#prop-propertyName-function 在这种情况下,它就像一个条件。
-
是的,它仍然需要两个参数:属性名称和返回值的函数。
-
@PaulAbbott 好的,如果我删除
false正在工作。
标签: javascript jquery