views:

32

answers:

2
function safe(){
    if($(this).is(':checked')){
        $("select[name='sort']").attr("disabled", "disabled");
        $("input[name='group']").attr("disabled", "disabled")
    } else {
        $("select[name='sort']").attr("disabled", false);
        $("input[name='group']").attr("disabled", false)
    }
}
$('input#safe').change(failsafe);

I have this function that I want to run onLoad as well as onChange, at the same time. Currently only onChange works, but onLoad, those fields remain enabled.

Thanks for your help!

+1  A: 

Not entirely sure if this is what you're looking for, but if you were hoping to run the safe() code when the page loads, try this.

Example: http://jsfiddle.net/ewNEc/

$(function() {

    function safe(){
        if( this.checked ){
            $("select[name='sort']").attr("disabled", "disabled");
            $("input[name='group']").attr("disabled", "disabled")
        } else {
            $("select[name='sort']").attr("disabled", false);
            $("input[name='group']").attr("disabled", false)
        }
    }
    $('input#safe').change(safe).triggerHandler("change");

});

Uses .triggerHandler() to fire the handler without changing the state.

patrick dw
A: 

I'm assuming here safe is the failsafe function you're referring to and it's just a posting mixup. Instead of .is(':checked') you can just use the .checked DOM property and make it very short, like this:

$(function() {
  $('input#safe').change(function() {
    $("select[name='sort'], input[name='group']").attr("disabled", this.checked);
  }).change();
});

The .change() call at the end triggers the change event handler you just bound, so it also runs on load.

Nick Craver