2016-06-29 5 views
1

ラベルが「はい」のラジオボタンが選択されると、クラスに「公開」クラスを追加する必要があります。これまでのところ私は自分のコードを設定して、必要なクラスを入力に適用するようにしましたが、 'reveal-if-active' divに 'reveled'クラスを追加する方法が必要です。最初の1つ後に複数のyes/noの質問があるので、このHTML構造全体が繰り返されます。だから、それぞれの「活発な場合に表示する」divは一意でなければなりません。ここでチェックされたラジオ/チェックボックス、複数のインスタンスに基づいて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

あなたは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>
は、

関連する問題