开发者

OnLoad and OnChange (jQuery)

开发者 https://www.devze.com 2023-01-14 05:58 出处:网络
function safe(){ if($(this).is(\':checked\')){ $(\"select[name=\'sort\']\").attr(\"disabled\", \"dis开发者_JAVA百科abled\");
function safe(){
    if($(this).is(':checked')){
        $("select[name='sort']").attr("disabled", "dis开发者_JAVA百科abled");
        $("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!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消