【发布时间】:2017-04-16 01:30:48
【问题描述】:
我想通过选中一个单选按钮来显示一个 DIV,当该 DIV 可见时,将使用 jquery 将 REQUIRED 属性添加到其 INPUT 字段中,但是如果未选中单选按钮并且隐藏了 DIV,则 REQUIRED 属性是也被删除了。但我不知道如何完成它
$(function() {
$('input[name=post-format]').on('click init-post-format', function() {
$('#private-box').toggle($('#private_office').prop('checked'));
}).trigger('init-post-format');
$('input[name=post-format]').on('click init-post-format', function() {
$('#public-box').toggle($('#public_office').prop('checked'));
}).trigger('init-post-format');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-top">
<div class="form-group">
<label class="btn btn-warning">
<input type="radio" name="acc-type" value="private_office" id="private_office"> Private Office
</label>
<label class="btn btn-warning">
<input type="radio" name="acc-type" value="public_office" id="public_office"> Public Office
</label>
</div>
<div id="private-box">
<div class="form-group">
<label for="ministry">Ministry</label>
<input type="text" id="ministry" name="ministry" class="form-control">
</div>
<div class="form-group">
<label for="ministry">Agency </label>
<input type="text" id="agency" name="agency" class="form-control">
</div>
</div>
<div id="public-box">
<div class="form-group">
<label for="ministry">State/ Region</label>
<input type="text" id="ministry_region" name="ministry_region" class="form-control">
</div>
<div class="form-group">
<label for="ministry">District</label>
<input type="text" id="ministry_district" name="ministry_district" class="form-control">
</div>
</div>
</div>
【问题讨论】:
-
@EbbySVHesse 您要显示或隐藏哪个 DIV?
-
@alfredo,我有 2 个 DIV和,2 单选按钮处理 2 个 DIV@alfredo,当单选按钮:#private-office 被选中时,它应该显示 DIV #private-box,与其他单选按钮相同。htr5 的答案中的代码显示了一种方法。要在 jquery 中设置属性,您可以执行类似的操作 $('#agency').prop('required', true);祝你好运!@alfredo,当 DIV 处于活动状态时,REQUIRED 属性会添加到输入字段中。