I have been trying to use different ways to code this jQuery part, but it's not working. I do have a list of cards with the first one that has a default class. The goal would be that each time I click on the button that says "Set as Default", I could set the class "default" on the parent "bgCreditcard" and disable the button at the same.
My issue is that I tried toggleClass
, but it was activating both the cards with the button "set as Default". I tried to disable with prop, but no luck too. Any ideas?
This is my HTML:
<div >
<div >
<div >
<div >
<p>Card 1</p>
<button disabled>Default</button>
</div>
</div>
</div>
<div >
<div >
<div >
<p>Card 2</p>
<button >Set as Default</button>
</div>
</div>
</div>
<div >
<div >
<div >
<p>Card 3</p>
<button >Set as Default</button>
</div>
</div>
</div>
</div>
Js:
$('.bg-default').click(function(){
$('.bgCreditcard').each(function(){
$(".active").removeClass("active");
$(this).addClass("active");
});
});
CodePudding user response:
Consider the following.
$(function() {
function clearDefault(card) {
$(card).removeClass("active");
$("button", card).prop("disabled", false).toggleClass("bg-btn-default bg-btn-disabled").html("Set as Default");
}
function addDefault(card) {
$(card).addClass("active");
$("button", card).prop("disabled", true).addClass("bg-btn-disabled").html("Default");
}
function setDefault(event) {
clearDefault($(".bgCreditcard.active"));
addDefault($(event.target).closest(".bgCreditcard"));
}
$(".bgCreditcard button").click(setDefault);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div >
<div >
<div >
<p>Card 1</p>
<button disabled="true">Default</button>
</div>
</div>
</div>
<div >
<div >
<div >
<p>Card 2</p>
<button >Set as Default</button>
</div>
</div>
</div>
<div >
<div >
<div >
<p>Card 3</p>
<button >Set as Default</button>
</div>
</div>
</div>
</div>
CodePudding user response:
You can try following code:
HTML:
<div >
<div >
<div >
<div >
<p>Card 1</p>
<button disabled>Default</button>
</div>
</div>
</div>
<div >
<div >
<div >
<p>Card 2</p>
<button >Set as Default</button>
</div>
</div>
</div>
<div >
<div >
<div >
<p>Card 3</p>
<button >Set as Default</button>
</div>
</div>
</div>
</div>
jQuery:
$(document).on('click', '.bg-btn' ,function(){
$('.bgCreditcard').removeClass('active');
$('.bgCreditcard').find('button').prop('disabled', false)
$('.bgCreditcard').find('button').removeClass('bg-btn-disabled')
$(this).closest('.bgCreditcard').addClass('active');
if($(this).closest('.bgCreditcard').hasClass('active')) {
$(this).prop('disabled', true);
$(this).addClass('bg-btn-disabled')
}
});