简体   繁体   中英

How to show a different form on click of a radio button in HTML by pure javascript

Here is my code. I want to display the login form on click of the login radio button and similarly signup form for sign up radio button.

I am getting an error

_blank.html:21 Uncaught TypeError: Cannot read property 'append' of null at loginUser at HTMLInputElement.onclick

_blank.html:28 Uncaught TypeError: Cannot read property 'append' of null at signupUser at HTMLInputElement.onclick

 function loginUser(logindiv){ console.log('login'); var newdivlogin = document.createElement('div'); newdivlogin.innerHTML = "<label>SignUp</label><br/>"+"<input placeholder='email'/><br/>"+"<input placeholder='password'/><br/>"; document.getElementById(logindiv).append(newdivlogin); } function signupUser(signupdiv){ console.log('signup'); var newdivsignup = document.createElement('div'); newdivsignup.innerHTML = "<label>SignUp</label><br/>"+"<input placeholder='email'/><br/>"+"<input placeholder='password'/><br/>"+"<input placeholder='name'/><br/>"; document.getElementById(signupdiv).append(newdivsignup); }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Links</title> </head> <body> <div class="user"> <h1>Please Login or Sign up if you are new User</h1> <input type="radio" id="login" name="radio" onclick="loginUser('user');" /><label>Login</label> <input type="radio" id="signup" name="radio" onclick="signupUser('user');" /><label>Sign Up</label><br/> </div> </body> </html>

Change class="user" to id="user"

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Links</title> </head> <body> <div id="user"> <h1>Please Login or Sign up if you are new User</h1> <input type="radio" id="login" name="radio" onclick="loginUser('user');" /><label>Login</label> <input type="radio" id="signup" name="radio" onclick="signupUser('user');" /><label>Sign Up</label><br/> </div> <script> function loginUser(logindiv){ console.log('login'); var newdivlogin = document.createElement('div'); newdivlogin.innerHTML = "<label>LogIn</label><br/>"+"<input placeholder='email'/><br/>"+"<input placeholder='password'/><br/>"; document.getElementById(logindiv).append(newdivlogin); } function signupUser(signupdiv){ console.log('signup'); var newdivsignup = document.createElement('div'); newdivsignup.innerHTML = "<label>SignUp</label><br/>"+"<input placeholder='email'/><br/>"+"<input placeholder='password'/><br/>"+"<input placeholder='name'/><br/>"; document.getElementById(signupdiv).append(newdivsignup); } </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM