Disable click for selected state in jQuery Toggle button

enter image description here

I just created an MVC 4 application in which I have a table with many rows. Each line has an active or inactive status.

If the record is active, it shows these buttons (for example, as in the second line 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 is in an inactive state, it shows these buttons (for example, as in the first line in the 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, active or inactive, it toggles buttons.

How can I prevent this with jQuery?

+3


source to share


1 answer


You have a bound click handler for the parent of the button, you can bind it to the button instead, except it has a class in it active

, 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'); {

    }

});

      

+3


source







All Articles