在迭代中基于类选择子元素

时间:2016-01-17 12:57:05

标签: javascript 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('');
    }
  });
});

我想在取消选中该复选框时清除所有input。第$(':input')行肯定是,但我应该选择input作为.form-sub子项的响应{ 1, 2, 3 } { 4, 5, 6 } 。我如何在Javascript中执行此操作?

1 个答案:

答案 0 :(得分:2)

替换此行

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();
    }
  });