natanel97 natanel97 - 2 months ago 13
HTML Question

JavaScript works only on first page

I have 3 forms (for login, registration and password recovery), and the following code:

document.addEventListener('DOMContentLoaded', function() {
var
login = {
user: 'afy-usr-log',
pass: 'afy-pas-log'
},

register = {
user: 'afy-usr-reg',
pass: 'afy-pas-reg',
mail: 'afy-eml-reg'
},

forget = {
user: 'afy-usr-psf',
captcha: 'afy-cpt-psf'
},

names = {
login: 'afy-usrlog',
register: 'afy-usrreg',
forget: 'afy-usrpsf'
};


document.querySelector('body').onkeyup = function() {
/* login */
if(document.getElementById(login['user']).value != '' && document.getElementById(login['pass']).value != '') {
document.getElementsByName(names['login'])[0].removeAttribute('disabled');
}
else {
document.getElementsByName(names['login'])[0].setAttribute('disabled', '');
}

/* register */
if(document.getElementById(register['user']).value != '' && document.getElementById(register['pass']).value != '' && document.getElementById(register['mail']).value != '') {
document.getElementsByName(names['register'])[0].removeAttribute('disabled');
}
else {
document.getElementsByName(names['register'])[0].setAttribute('disabled', '');
}

/* forget password */
if(document.getElementById(forget['user']).value != '' && document.getElementById(forget['captcha']).value != '') {
document.getElementsByName(names['forget'])[0].removeAttribute('disabled');
}
else {
document.getElementsByName(names['forget'])[0].setAttribute('disabled', '');
}
}
});


This code works perfectly on my main page,
index.php
, which contains only register form and login form, but if I add
?v=1
(which contains only password recovery form) to the address line, the script won't work anymore. (actually, it can work, if I replace the last if/else with the first one, but then the others won't work - the 1st and the 2nd if/else).

How can I solve this?

Answer

Try to change your code like this:

document.querySelector('body').onkeyup = function() {
        /* login */
        if(
        (null !== document.getElementById(login['user']) &&                
         '' !== document.getElementById(login['user']).value) && 
        (null !== document.getElementById(login['pass']) &&  
         '' !== document.getElementById(login['pass']).value) {
            document.getElementsByName(names['login'])[0].removeAttribute('disabled');
        }
        else ...
Comments