OnLoad and OnChange (jQuery)

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, these fields remain enabled.

Thank you for your help!

+3
source share
2 answers

Not quite sure if this is what you are looking for, but if you were hoping to run the code safe()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");

});

Used .triggerHandler()to start a handler without changing state.

+3
source

, safe - failsafe, , . .is(':checked') .checked DOM , :

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

.change() change, , .

+2

Source: https://habr.com/ru/post/1763259/


All Articles