My "interact.html" just has Login form and two buttons, which called "Login" and "Register" respectively, if users want to create a new account, they need to click the button "Register", then the Login form will be changed to Register form by using Fetch API. If users want to change the Register form to the Login form again, they can click the button "Login", then the Login form will be changed to Register form by using Fetch API.
I write a file "accounts.js" to deal with the event on "interact.html"
First get the element:
get the "login-form"
const form = document.getElementById('login-form');
get login button
const log = document.getElementsByClassName('log-reg')[0];
get register button
const reg = document.getElementsByClassName('log-reg')[2];
Here is the the part of Fetch API
Change Register form to Login form
log.addEventListener('click', function(event){
fetch('http://127.0.0.1:8090/interact?page=login')
.then(response => response.text())
.then(body =>
form.innerHTML=body
)
});
Change Login form to Register form
reg.addEventListener('click', function(event){
fetch('http://127.0.0.1:8090/interact?page=register')
.then(response => response.text())
.then(body =>
form.innerHTML=body
)
});
Then Node.js(express) will return the html
app.get('/interact',(req,res) => {
if(req.query.page==='register'){
res.sendFile(path.join(__dirname+'/public/register-form.html'));
}
else if (req.query.page==='login'){
res.sendFile(path.join(__dirname+'/public/login-form.html'));
}
else{
res.sendFile(path.join(__dirname+'/public/interact.html'));
}
})
This is "register-form.html"
<body>
<div class="mb-3">
<label for="setusername" class="form-label" style="font-size: 20px;">Set User name:</label>
<br>
<input class="form-control">
</div>
<br>
<div class="mb-3">
<label for="setpassword" class="form-label" style="font-size: 20px;">Set Password:</label>
<br>
<input type="password" class="form-control" id="setpassword">
</div>
<div class="mb-3">
<label for="ensure" class="form-label" style="font-size: 20px;">Ensure Password:</label>
<br>
<input type="password" class="form-control" id="ensure">
</div>
<br>
<button type="submit" class="btn btn-primary" id = "create">Register</button>
</body>
The "login-form.html" is similar to the "register-form.html"
After the Login form or Register form being changed, the element in "login-form.html" and "register-form.html" which is updated to "interact.html" by fetch() API can not be got.
can not get element "create"
const create = document.getElementById('create');
Because when I write
create.addEventListener('click',function(event){})
The browser will report Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
which means element"create" can not be got.
I wonder how to solve this problem or any other ways to implement the same approach.