kez
kez

Reputation: 2313

Disable click for selected state in Jquery Toggle button

enter image description here

I just created a MVC 4 application in which I have a table with many rows. Each row has an Active or an Inactive status.

If the record is in an active state it's showing this buttons (like as in the 2nd row in the picture above).

<button 
    class="btn btn-xs active btn-primary" 
    data-HEI_ID = @item.HEI_ID 
    data-status = "true">Active
</button>  
<button 
    class="btn btn-xs inactiveColor btn-default" 
    data-HEI_ID = @item.HEI_ID 
    data-status = "false">Inactive
</button>

If it's in inactive state it's showing this buttons (like as in the 1st row in picture above):

<button 
    class="btn btn-xs btn-default" 
    data-HEI_ID = @item.HEI_ID 
    data-status = "true">Active
</button>                       
<button 
    class="btn btn-xs inactiveColor btn-primary active" 
    data-HEI_ID = @item.HEI_ID 
    data-status = "false">Inactive
</button>

Here is the jQuery function:

$('.btn-toggle').click(function () {

    $(this).find('.btn').toggleClass('active');

    if ($(this).find('.btn-primary').size() > 0) {
        $(this).find('.btn').toggleClass('btn-primary');
    }
    if ($(this).find('.btn-danger').size() > 0) {
        $(this).find('.btn').toggleClass('btn-danger');
    }
    if ($(this).find('.btn-success').size() > 0) {
        $(this).find('.btn').toggleClass('btn-success');
    }
    if ($(this).find('.btn-info').size() > 0) {
        $(this).find('.btn').toggleClass('btn-info');
    }

    $(this).find('.btn').toggleClass('btn-default'); {

    }

});

But when I click the selected state, either active or inactive, it is switching the buttons.

How to prevent this using jQuery?

Upvotes: 3

Views: 1088

Answers (1)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You have binded click handler for the parent element of button instead you can bind it for button except having class active in it as this indicates the selected state.

$('.btn.btn-xs').click(function () {
    //return if clicked button have class active
    if($(this).hasClass('active'))
       return false;

    var $parent = $(this).closest('.btn-toggle');
    $parent.find('.btn').toggleClass('active');
    if ($parent.find('.btn-primary').size() > 0) {

        $parent.find('.btn').toggleClass('btn-primary');
    }
    if ($parent.find('.btn-danger').size() > 0) {
        $parent.find('.btn').toggleClass('btn-danger');
    }
    if ($parent.find('.btn-success').size() > 0) {
        $parent.find('.btn').toggleClass('btn-success');
    }
    if ($parent.find('.btn-info').size() > 0) {
        $parent.find('.btn').toggleClass('btn-info');
    }

    $parent.find('.btn').toggleClass('btn-default'); {

    }

});

Upvotes: 3

Related Questions