根据已检查的radio / checkbox,多个实例显示div

时间:2016-06-29 16:06:21

标签: javascript jquery html css checkbox

我必须添加课程'透露'一个div,一旦带有标签的单选按钮'是'已被选中。到目前为止,我已经设置了我的代码,以便我应用所需的'将要显示的输入类,但我需要有一种方法来添加类'显示'如果显示 - 如果活跃' DIV。整个HTML结构将重复,因为在第一个之后会有多个是/否问题。因此,每个“如果活跃的话”都会显示出来。 div必须是唯一的。

这是我需要使用的HTML结构:

<div class="form-group two-column">
  <input id="a1" type="radio" name="ayesno" value="1">
  <label for="a1">yes</label>
</div>
<div class="form-group two-column">
  <input id="a2" type="radio" name="ayesno" value="2">
  <label for="a2">no</label>
</div>
<div class="reveal-if-active">
  <label for="how-many-people">If <strong>yes</strong> how many people?</label>
  <input type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>

这是我到目前为止的JS:

var FormStuff = {

  init: function() {
    this.applyConditionalRequired();
    this.bindUIActions();
  },

  bindUIActions: function() {
    $("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
  },

  applyConditionalRequired: function() {

    $(".require-if-active").each(function() {
      var el = $(this);
      if ($(el.data("require-pair")).is(":checked")) {
        el.prop("required", true);
        $('[data-id=' + $('input:checked').prop('id') + ']').addClass('reveal'); 

      } else {
        el.prop("required", false);
        el.removeClass("revealed");
      }
    });

  }

};

FormStuff.init();

1 个答案:

答案 0 :(得分:1)

您可以使用el.closest('div.reveal-if-active')

var FormStuff = {

  init: function () {
    this.applyConditionalRequired();
    this.bindUIActions();
  },

  bindUIActions: function () {
    $("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
  },

  applyConditionalRequired: function () {

    $(".require-if-active").each(function () {
      var el = $(this);
      if ($(el.data("require-pair")).is(":checked")) {
        el.prop("required", true);
        el.closest('div.reveal-if-active').addClass("revealed");

      } else {
        el.prop("required", false);
        el.closest('div.reveal-if-active').removeClass("revealed");
      }
    });

  }

};


$(function () {
  FormStuff.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="form-group two-column">
    <input id="a1" type="radio" name="ayesno" value="1">
    <label for="a1">yes</label>
</div>
<div class="form-group two-column">
    <input id="a2" type="radio" name="ayesno" value="2">
    <label for="a2">no</label>
</div>
<div class="reveal-if-active">
    <label for="i1">If <strong>yes</strong> how many people?</label>
    <input id="i1" type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>