Horratio Horratio - 7 months ago 15
Javascript Question

jQuery - Remove prop if parent has class

I'm building a form and I use jquery validate to check the fields.
I have 4 sub categories, when you click on one it obtains the class "choice" and a input text is appearing to specify the amount. I tried to make a condition that if the item had the class "choice", it adds 'required' to the input. But I cannot remove it if another item is selected. Here is my code :

jQuery('.offres_abo').click(function() {
jQuery('.offres_abo').removeClass('choice');
jQuery(this).addClass('choice');
if (jQuery('.offres_abo').hasClass('choice')) {
jQuery(".offres_abo.choice input").prop('required', true);
} else {
jQuery(".offres_abo.choice input").prop('required', false);
}
});





<div class="row">
<div class="col-md-3 offres_abo choice">
<button type="button" name="button">
<span class="item_name"><p>Offre d&#8217;essai<br />
3 COLIS/AN</p>
</span>
<span class="item_desc"><p>1 colis par mois (excepté juillet)</p></span>
<span class="item_price">39 €/an</span>
<span class="item_price_comp"></span>
</button>
<div class="nb_items">
<span>Quantité x</span>
<input id="offre_bronze" type="text" name="offre_bronze" required>
</div>
</div>

Answer

Select items you need to modify before removing the class

jQuery('.offres_abo').click(function(){
    jQuery('.offres_abo.choice')
        .removeClass('choice')
        .find('input')
        .prop('required', false);

    jQuery(this)
        .addClass('choice')
        .find('input')
        .prop('required', true);
});