H
H
helga1123582018-12-15 19:54:18
JavaScript
helga112358, 2018-12-15 19:54:18

A global variable changes in a nested function, but outside remains the same?

The global variable does not change outside the nested function, you need to use the checkName variable in another function, but console.log returns false. Although the validation is successful. Please tell me what could be the reason?

var checkName = false;
         
     $('.userName').blur(function() {
            if($(this).val() != '') {
                var pattern = /^[a-zA-Z]+$/; 
                if(pattern.test($(this).val())){
                    checkName = true;
                    $('.nameValid').css({'display' : 'none'});
                } else {
                    $('.nameValid').css({'display' : 'block'});
                    $('.nameValid').text('Invalid name!');
                }
            } else {
                $('.nameValid').css({'display' : 'block'});
                $('.nameValid').text('Name must be filled!');
            }
        });
        console.log(checkName);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-12-15
@Rsa97

blur() just hangs a handler on the .userName elements and returns immediately.
The callback function that can change checkName will only be called on an event.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question