我有一张表格,上面有一个很大的搜索字段。
还有一个
钟声和哨声
复选框-勾选此选项后,将显示3个附加字段。
我希望将form方法设置为get而不是post。
提交表单时,URL最终为:
test.php?q=tree&whistles=y&exa=any&fmt=cat&opt=img
我想改变的是,如果没有勾选“钟声和哨声”复选框,那么表单中的其他3个字段(包括“哨声”复选框在内的4个字段)不会被提交,因此URL显示为:
test.php?q=tree
然后,如果用户勾选复选框,从而希望搜索其他内容,则这些字段将包含在搜索中。
这是我的起始代码:
// show / hide bells and whistles checkbox
$(function() {
$('#whistles').change(function() {
if ($(this).is(":checked")) {
$('#options').show();
} else {
$('#options').hide();
}
});
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<form action='test.php' method='get'>
<input type='text' class='form-control form-control-lg' id='q' name='q' placeholder='Search'>
<div style='margin-top:5px;'><input type='checkbox' id='whistles' name='whistles' value='y' /> <label for='whistles'>Show Bells and Whistles</label></div>
<p></p>
<div id='options' style='display:none' class="alert alert-secondary">
<div class='form-row'>
<div class='form group col-md-4'>
<label for='exa'>Match Type</label>
<select name='exa' id='exa' class='form-control form-control-sm'>
<option value='' disabled='disabled'>Match</option>
<option value='any'>Any</option>
<option value='exact'>Exact</option>
</select>
</div>
<div class='form group col-md-4'>
<label for='fmt'>Format</label>
<select name='fmt' id='fmt' class='form-control form-control-sm'>
<option value='' disabled='disabled'>Format</option>
<option selected='selected' value='cat'>Category</option>
<option value='subcat'>Subcategory</option>
</select>
</div>
<div class='form group col-md-4'>
<label for='opt'>Output</label>
<select name='opt' id='opt' class='form-control form-control-sm'>
<option value='' disabled='disabled'>Output</option>
<option selected='selected' value='img'>Image</option>
<option value='emj'>Font</option>
</select>
</div>
</div>
</div>
<button type='submit' class='btn btn-success' style='margin:5px 0px 15px 0px;'>Go!</button>
</form>
我不知道该怎么做。可能需要使用jquery detach()吗?如果是这样的话,不幸的是,我对我将如何做到这一点一无所知。
通过执行以下操作修复:
我添加了这个JS来检查提交页面时是否选中了复选框。如果是,则启用其他表单字段。如果没有,禁用它们:
var foo1 = document.getElementById("whistles").checked;
if (foo1 == true) { document.getElementById("exa").disabled = false; } else { document.getElementById("exa").disabled = true; }
if (foo1 == true) { document.getElementById("fmt").disabled = false; } else { document.getElementById("fmt").disabled = true; }
if (foo1 == true) { document.getElementById("opt").disabled = false; } else { document.getElementById("opt").disabled = true; }
然后我们从答案中得到JS(
https://stackoverflow.com/a/50778666/4532066
)选中/取消选中复选框时切换启用/禁用属性。