[英]Select children elements based on class in iteration
Either using Vanilla Javascript or jQuery. 使用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('');
}
});
});
I want to clear all input
when the checkbox is unchecked. 取消选中复选框时,我想清除所有
input
。 The line $(':input')
is definitely, but that's where I should select the responding input
s which are the children of .form-sub
. $(':input')
绝对是,但这是我应该选择响应input
s的地方,它们是.form-sub
。 How do I do that in Javascript? 如何在Javascript中做到这一点?
replace this line 替换这条线
var parentForm = '#' + subForm.dataset.target;
by 通过
var parentForm = $( subForm ).prev();
and update the change
event as 并更新
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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.