我希望仅在选择某些选择选项时才显示表单的一部分。我已经能够使用以下html代码和jquery脚本实现此目的
$(document).ready(function displayform() {
//var dept = $("#dept option:selected").text();
$('select').change(function() {
if ($(this).val() != 'administration') {
$('#teacred').show();
} else {
$('#teacred').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="department" class="col-md-4 control-label">Department</label>
<div class="col-md-6">
<select name="department" id="dept" class="form-control" required autofocus>
<option class="text-muted">-- Select Department --</option>
<option value="administration">Adminstration</option>
<option value="ict">ICT</option>
</select>
</div>
</div>
<div class="form-group" id="position">
<label for="position" class="col-md-4 control-label">Position</label>
<div class="col-md-6">
<select name="position" class="form-control" required autofocus>
<option></option>
<option value="hod">Head of Department</option>
<option value="staff">Staff</option>
</select>
</div>
</div>
<div class="col-md-12" id="teacred">
<div class="form-group">
<label for="username" class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input id="username" type="username" class="form-control" name="username" value="{{ old('username') }}" required>
</div>
</div>
</div>
挑战在于,当我选择一个部门时代码有效,选择一个职位也会影响教学div的显示。我如何确保只有部门选择选项才能确定何时显示或隐藏了食堂div?
答案 0 :(得分:1)
$('select')
会选择不是您想要的所有<select>
元素,更改为第二次选择会触发更改事件并显示$('#teacred')
$('#dept')
仅定位部门选择。
$(document).ready(function displayform() {
//var dept = $("#dept option:selected").text();
$('#dept').change(function() {
if ($(this).val() != 'administration') {
$('#teacred').show();
} else {
$('#teacred').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="department" class="col-md-4 control-label">Department</label>
<div class="col-md-6">
<select name="department" id="dept" class="form-control" required autofocus>
<option class="text-muted">-- Select Department --</option>
<option value="administration">Adminstration</option>
<option value="ict">ICT</option>
</select>
</div>
</div>
<div class="form-group" id="position">
<label for="position" class="col-md-4 control-label">Position</label>
<div class="col-md-6">
<select name="position" class="form-control" required autofocus>
<option></option>
<option value="hod">Head of Department</option>
<option value="staff">Staff</option>
</select>
</div>
</div>
<div class="col-md-12" id="teacred">
<div class="form-group">
<label for="username" class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input id="username" type="username" class="form-control" name="username" value="{{ old('username') }}" required>
</div>
</div>
</div>