简体   繁体   中英

jQuery unbinding click event on a radio button that is already selected

I am trying to create some parametric filters but i do not want to invoke the function that makes my search AJAX call when a radio button filter is already selected.

$('#contentType input:enabled').bind('click', function(e){
    var $this = $(this),
        $type = this.type,
        $id = this.id;
    if ($type === 'radio') {
        if ($id === 'allContent'){
            sFrm.$boxes.attr({'checked': false});
            sFrm.$specificRadio.attr({'disabled': true});   
            searchAjax();
            removeFilter();
        }
    } else if ($type === 'checkbox') {
        if (sFrm.$boxes.filter(':checked').length === 0) {
            sFrm.$allRadio.trigger('click');        
        } else {
            var filterConfig = {
                index: $('.subFilter').index($this),
                txt: jQuery.trim($this.parent().text())
            }                   
            sFrm.$allRadio.attr({'checked': false});        
            sFrm.$specificRadio.attr({'disabled': false, 'checked': true}); 
            searchAjax();
            if ($this.is(':checked')) {
                addFilter(filterConfig);
            } else {
                removeFilter(filterConfig.index);
            }               
        }           
    }   
});

So the jQuery above looks at ALL enabled inputs in the collection and when a user clicks the allContent radio button the searchAjax function is invoked.

This is correct when said radio button is not already selected/checked. At the moment the function is still invoked when the button is selected and i would like to stop this behaviour but cannot figure out how?

EDIT

Not sure i explained correctly. Hopefully this jsFiddle will help:

http://jsfiddle.net/QsbRp/3/

Basically if All content types is checked already and is clicked when checked then searchAjax should not be invoked. It currently invokes the function.

When it is not checked and clicked then it should behave as it is now (disable sibling radio button and uncheck all associated checkboxes).

Add at the top of your handler:

if ($this.is(":checked")) {
    return;
}

The event handler will return and not execute the rest of the function if the radio button is currently selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM