Skip to content
Advertisement

Remove class when click another button using JQuery

I’m figure out for how to remove class selected when clicking other button. I’ve made code below but still not working. Can anyone help me?

EDIT

The case study, I have 2 choice boxes. box 1 and box 2. each box has 2 options. When click on box 1 option 1 and move to box 1 option 2, it works fine. But when I click box 2 option 1, the options in box 1 should not change. So there will be 2 buttons that have the selected class, namely box 1 choice 2 and box 2 choice 1

enter image description here

$(document).ready(function(){
  $('.box-1 button, .box-2 button').on('click', function(){
    $(this).addClass('selected');
    $('.box-1 button, .box-2 button').not(this).removeClass('selected');
  });
});
button{
  border:none;
  background-color:#1f45;
  padding: .5rem 2.5rem;
  border-radius: 2rem;
}

.box-1{
  margin-bottom: 15px;
}

button.selected{
  background-color: #578889;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Box 1 Choice</h3>
<div class="box-1">
  <button>Box 1 Option 1</button>
  <button>Box 1 Option 2</button>
</div>

<h3>Box 2 Choice</h3>
<div class="box-2">
  <button>Box 2 Option 1</button>
  <button>Box 2 Option 2</button>
</div>

Advertisement

Answer

You can use .not(this) to exclude button which is clicked and remove selected class from there

Demo Code :

$(document).ready(function() {
  $('button').on('click', function() {
    $(this).addClass('selected');
    $(this).closest('div').find('button').not(this).removeClass('selected');
  });
});
button {
  border: none;
  background-color: #1f45;
  padding: .5rem 2.5rem;
  border-radius: 2rem;
}

button.selected {
  background-color: #578889;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-1">
  <button>Box 1 Option 1</button>
  <button>Box 1 Option 2</button>
</div>

<div class="box-2">
  <button>Box 2 Option 1</button>
  <button>Box 2 Option 2</button>
</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement