使用 Vanilla Javascript 或 jQuery。
// html
<input type="checkbox" value="1" checked="checked" name="patient[event_type_ids][]" id="patient_event_type_ids_1"> Bleeding puncture
<div data-target="patient_event_type_ids_1" class="form-sub">
<div class="form-group">
<input type="radio" value="true" name="patient[blood_aspirated]" id="patient_blood_aspirated_true"> Yes
<input type="radio" value="false" checked="checked" name="patient[blood_aspirated]" id="patient_blood_aspirated_false"> No
</div>
<div class="form-group">
<input type="radio" value="positive" name="patient[iv_test]" id="patient_iv_test_positive"> Positive
<input type="radio" value="negative" checked="checked" name="patient[iv_test]" id="patient_iv_test_negative"> Negative
</div>
</div>
<input type="checkbox" value="1" checked="checked" name="patient[event_type_ids][]" id="patient_event_type_ids_2"> Vascular puncture
<div data-target="patient_event_type_ids_2" class="form-sub">
<div class="form-group">
<input type="radio" value="true" name="patient[abc]" id="patient_abc_true"> Yes
<input type="radio" value="false" checked="checked" name="patient[abc]" id="patient_abc_false"> No
</div>
<div class="form-group">
<input type="radio" value="positive" name="patient[xyz]" id="patient_xyz_positive"> Positive
<input type="radio" value="negative" checked="checked" name="patient[xyz]" id="patient_xyz_negative"> Negative
</div>
</div>
// javascript
var subForms = $('.form-sub');
subForms.each(function() {
var subForm = this;
var parentForm = '#' + subForm.dataset.target;
if ($(parentForm).prop('checked')) {
$(subForm).show();
} else {
$(subForm).hide();
}
$(parentForm).change(function(){
if($(this).prop("checked")) {
$(subForm).show();
} else {
$(subForm).hide();
$(':input')
.not(':button, :submit, :reset, :hidden')
.removeAttr('checked')
.removeAttr('selected')
.not(':checkbox, :radio, select')
.val('');
}
});
});
我想清除所有input
当复选框未选中时。线路$(':input')
肯定是,但那是我应该选择响应的地方 input
s 是 .form-sub
的 child .我如何在 Javascript 中做到这一点?
最佳答案
替换这一行
var parentForm = '#' + subForm.dataset.target;
由
var parentForm = $( subForm ).prev();
并将change
事件更新为
if ( parentForm.prop('checked')) {
$(subForm).show();
} else {
$(subForm).hide();
}
parentForm.change(function(){
if($(this).prop("checked")) {
$(subForm).show();
} else {
$(subForm).find(':input')
.not(':button, :submit, :reset, :hidden')
.removeAttr('checked')
.removeAttr('selected')
.not(':checkbox, :radio, select')
.val('');
$(subForm).hide();
}
});
关于javascript - 在迭代中根据类选择子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34838562/