vasigorc
vasigorc

Reputation: 962

jQuery: input:checkbox change() only fired on browser reload

I apologize if this seems ridiculously easy, but I cannot find where the problem lies.

This is the part of html that I am trying to control using jQuery:

<table id="my_table" class="tableCommon">
            <tbody>
                <tr>
                    <td class="control" colspan="3"><a name="SOME_NAME"></a><input value="1" name="SOME_NAME" disabled="" class="checkbox" type="checkbox">
                        <span class="checkbox-label">This is a checkbox label</span>
                    </td>
                </tr>

This is the jQuery part (the opening script tag follows table's closing tag):

jQuery(document).ready(function(){

    //other stuff before it
    function changedValue(newVal){
        jQuery('table#my_table tr td:first-child input:checkbox').each(function(){
            if(this.name !== newVal){
                this.attr('checked', false);                
            }
        });
    }
    jQuery('table#my_table tr td:first-child input:checkbox').change(changedValue(this.name));
});

I have debug breakpoints at both the selector with change() listener and the if statement inside changedValue function. When one tries checking the check-boxes, none of the breakpoints are reached. Code does stop at them when on page reload. There are other handlers in the same jQuery block that I omitted but which work fine (on event basis).

jQuery version used is 1.4.2 browser: Firefox Developer Edition 62.0b12

Upvotes: 0

Views: 35

Answers (1)

Taplar
Taplar

Reputation: 24965

jQuery('table#my_table tr td:first-child input:checkbox').change(changedValue(this.name));

You are invoking the method changedValue here, because you are calling it with arguments. So what is being bound as a handler is the result returned from the function, which is undefined. You should modify your binding to bind properly.

//accept in the event that happened
function changedValue(e){
    //get the value off of the element that was changed, which exists on the event
    var newVal = e.target.name;

    //reduced the each to a filter
    jQuery('table#my_table tr td:first-child input:checkbox')
      .filter(function(){ return this.name != newVal; })
      .attr('checked', false);
}

//give change the function reference
jQuery('table#my_table tr td:first-child input:checkbox').change(changedValue);

Upvotes: 3

Related Questions