Jquery combine condition and focusout

147 Views Asked by At

I have two conditions which (if they are true) execute the same function (one of them is 'focusout' event):

$(document).ready(function () {


    if($('#id1').val().length != 0 ) {

        $('id2').val($('#id1').val());

    }

    $(document).on('focusout', '#id1', function() {

        $('id2').val($('#id1').val());

    });

})

I was wondering if there is a way to combine first condition and 'focusout' event in way like:

    if(condition1 OR in case of 'focusout' event) 
          { 
             do the same;
          }
1

There are 1 best solutions below

1
Martin Geldart On

I think the best you'll get is calling the same function but having two callers:

if ($('#id1').val().length != 0 ) myFunction();
$(document).on('focusout', '#id1', myFunction);

function myFunction() {
    $('id2').val($('#id1').val());
}

You can't combine an event handler with a conditional statement.