0

Using jQuery I want to switch class button when user click on it. This is the button code I have right now

<button type="button" class="btn btn-success btn-bordered" id="toggle-job">Grab this work</button>

Below the code to handle the button click

$('#toggle-job').click(function(e){
    if ( $( this ).hasClass( "btn-success" ) ) {
        $( this ).removeClass( "btn-success" ).addClass( "btn-custom" );
        $( this ).text("Drop this work");
    };
    if ( $( this ).hasClass( "btn-custom" ) ) {
        $( this ).removeClass( "btn-custom" ).addClass( "btn-success" );
        $( this ).text("Grab this work");
    };
    $( "#action-box" ).toggle();
    $( "#photoCrop" ).toggle();
});

The toggle code works properly...so the related divs show or hide I'm pretty sure I'm doing some silly error...but I'm not able to figure out what I'm doing wrong. Thanks a lot for any suggestion

Federico
  • 319
  • 2
  • 14
  • Possible duplicate of [Add/remove class to a button](https://stackoverflow.com/questions/43285555/add-remove-class-to-a-button) – Kiran Joshi Oct 20 '18 at 10:18

1 Answers1

2

Just change your second if statement to an else if statement, that should work.

Right now your first if case changes the class to btn-custom, but right after that the second if changes it back to btn-success.

twain
  • 1,305
  • 11
  • 16
  • I'm really stupid! Thanks a lot twain. By the way...there could be a more elegant way to switch class? – Federico Oct 20 '18 at 10:33
  • No problem, you're welcome. For a more easy / elegant way have a look at this: https://stackoverflow.com/questions/7002039/easiest-way-to-toggle-2-classes-in-jquery – twain Oct 20 '18 at 10:50