如何使用Toggle添加和删除必需属性
我的用户可以访问表单。
为了简化任务,我放了一个可选择的列表,但如果答案不在列表中,他们可以手动添加一个原因
默认情况下需要可选列表,但如果用户访问文本字段,则需要该列表,并且不再需要列表(反之亦然)。
HTML:
Select 1 2 3 4 5 Other
JS:
$('input[name="messagetick"]').click(function() { $('#motif-reject').toggle(this.checked); });
你可以看到JsFiddle: https ://jsfiddle.net/rkkdhant/
我不知道如何处理切换,你能帮助我吗?
您可以使用相同的布尔值来toggle
textarea: this.checked
。 然后将required
属性设置为motif
select和motif-text
textarea,如下所示:
$('input[name="messagetick"]').click(function () { $('#motif-reject').toggle(this.checked); $("textarea[name='motif-text']").prop("required", this.checked); $("select[name='motif']").prop("required", !this.checked); });
请尝试以下代码段:
$('input[name="messagetick"]').click(function () { $('#motif-reject').toggle(this.checked); $("textarea[name='motif-text']").prop("required", this.checked); $("select[name='motif']").prop("required", !this.checked); console.log("Checkbox check: " + this.checked); console.log("Textarea required: " + $("textarea[name='motif-text']").prop("required")); console.log("Select required: " + $("select[name='motif']").prop("required")); console.log("----------------------------------"); });
Other
Html:
Other
JS:
if(!$('#messagetick2').is(':checked')){ $("select").prop('required',true); } $('input[name="messagetick"]').click(function() { $("select").prop('required',false); $('#motif-reject').toggle(this.checked); $("textarea").prop('required',true); });
可以检查选择与否的位置。 并根据该检查提出所需的真假。
试试这个JSFIFFLE
$('input[name="messagetick"]').click(function() { $('#motif-reject').toggle(this.checked); if ($("#messagetick2").is(":checked")) { $('#motif').prop('disabled', 'disabled'); $('#motif').prop('required', ''); }else{ $('#motif').prop('disabled', ''); $('#motif').prop('required', 'required'); } });