我的用户可以访问表单。
为了简化任务,我放置了一个可选择的列表,但如果答案不在列表中,他们可以手动添加原因
默认情况下,可选列表是必需的,但如果用户访问文本字段,则该列表将成为必需的,并且不再需要该列表(反之亦然)。
HTML:
<div class="form-group">
<select name="motif" class="form-control input-lg" required>
<option selected="true" disabled="disabled" value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div class="form-group">
<input name="messagetick" id="messagetick2" type="checkbox" value="yes" /> Other
</div>
<div id="motif-reject" class="form-group" style="display: none">
<textarea class="form-control" rows="5" placeholder="reason" name="motif-text"></textarea>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
$('input[name="messagetick"]').click(function() {
$('#motif-reject').toggle(this.checked);
});
Run Code Online (Sandbox Code Playgroud)
你可以看到JsFiddle: https ://jsfiddle.net/rkkdhant/
我不知道如何使用切换开关,你能帮我吗?
您可以使用与toggletextarea:相同的布尔值this.checked。然后将required属性设置为您的motif选择和motif-text文本区域,如下所示:
$('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);
});
Run Code Online (Sandbox Code Playgroud)
请尝试以下代码片段:
$('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);
});
Run Code Online (Sandbox Code Playgroud)
$('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("----------------------------------");
});Run Code Online (Sandbox Code Playgroud)