Why javascript function don't work for onclick event - javascript

I am trying to execute a event to verify if 2 input values are equals, but the javascript function dont works
I want to compare the valus of 2 text input box in realtime, like webforms, when the user type into the text box, the web says if the values match or not
This is the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 id="resultado">Resultado</h2>
<div >
<label id="passwordlabel" for="password1">Contraseña</label>
<input name="password" type="text" id="password" placeholder="Contraseña" required>
<div class="invalid-feedback">
Contraseña no válida.
</div>
</div>
<div >
<label for="password2">Confirme Contraseña</label>
<input name="password2" type="password" id="password2" onclick="pass()" placeholder="Repita contraseña" required>
<div class="invalid-feedback">
Las contraseñas deben ser iguales.
</div>
</div>
<script src="js/password-validation.js"></script>
</body>
</html>
And this is the JS file
function pass() {
'use strict'
result=document.getElementById("resultado");
result.innerHTML = "el java script sirve";
var inputPassword = document.getElementById('password').value;
var inputPassword2 = document.getElementById('password2').value;
if ( inputPassword != inputPassword2) {
result.innerHTML = "values don't match";
}
else{
result.innerHTML = "values match";
}
})
Thank you

1- At the end of your function you have an unnecessary parentheses )
2- If you use use strict you need to declare your variables: var result = ...
3- Probably is conceptually wrong to check the two fields with an onclick on textbox, but this is not a formal error.
function pass() {
'use strict'
var result = document.getElementById("resultado");
result.innerHTML = "el java script sirve";
var inputPassword = document.getElementById('password').value;
var inputPassword2 = document.getElementById('password2').value;
if (inputPassword != inputPassword2) {
result.innerHTML = "values don't match";
} else {
result.innerHTML = "values match";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 id="resultado">Resultado</h2>
<div >
<label id="passwordlabel" for="password1">Contraseña</label>
<input name="password" type="text" id="password" placeholder="Contraseña" required>
<div class="invalid-feedback">
Contraseña no válida.
</div>
</div>
<div >
<label for="password2">Confirme Contraseña</label>
<input name="password2" type="password" id="password2" onclick="pass()" placeholder="Repita contraseña" required>
<div class="invalid-feedback">
Las contraseñas deben ser iguales.
</div>
</div>
<script src="js/password-validation.js"></script>
</body>
</html>

Related

How do we apply Bootstrap classes to JavaScript Error messages and make them stay on the screen when a form submit button is clicked?

I am trying to figure out how to make Javascript error messages be displayed in the DOM and stay there until valid information is added into the form inputs. Right now they appear for a brief moment and then disappear. On top of that, I have to use Bootstrap 5 to stylize the JavaScript Error messages. I've been trying to figure this out all day and I haven't had any luck.
I have my HTML and Javascript down below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login Form</title>
<link rel="stylesheet" href="login/login.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<main>
<h1 class="text-primary">Login</h1>
<form id="login_form" name="login_form" method="get">
<div>
<label for="email1">Email:</label>
<input name="email" type="email" autocomplete="email" id="email" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label for="password">Password:</label>
<input name="password" type="password" autocomplete="password" id="password" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label> </label>
<button type="submit" class="btn btn-primary" id="login">Login
</div>
</form>
</main>
</main>
<script defer src="login/login.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
const $ = selector => document.querySelector(selector);
document.addEventListener("DOMContentLoaded", () => {
$("#login").addEventListener("click", () => {
// get values user entered in textboxes
const email = $("#email");
const password = $("#password");
// create a Boolean variable to keep track of invalid entries
let isValid = true;
// check user entries - add text to error message if invalid
if (email.value == "" || password.value == "") {
email.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
password.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
return false;
} else {
email.nextElementSibling.textContent = "";
password.nextElementSibling.textContent = "";
}
if (email.value == "admin#example.com" && password.value == "password") {
document.writeln("Welcome back Admin!")
} else {
document.writeln("That email and password doesn't seem to be right. Try again.")
}
// submit the form if all entries are valid
if (isValid) {
$("#login_form").submit();
}
});
});

Trying to import one js file to another

I managed to import a function from my main.js to my signin.js, but for some reason, I get this error on my sign in html page Cannot read properties of null (reading 'addEventListener')
and the function for the signin js is not working and I need to import the function of the main.js as the signin js function relys on the main.js function to work.
HTML 1 - signin js
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../js/main.js" type="module"></script>
<script src="../js/signin.js" type="module"></script>
<title>Sign in</title>
</head>
<body>
<main>
<form class="form-container">
<input class="email" type="text" placeholder ="Email Address">
<input class="password" type="password" placeholder ="Password">
Sign In
Register
</form>
</main>
</body>
signin.js imported function
//import function
import { validate } from "../js/main.js";
let registration = validate();
let signInbtn = document.querySelector(".sign-in");
signInbtn.addEventListener("click", check);
function check(){
let storedEmail = localStorage.getItem('email');
let storedPw = localStorage.getItem("password");
let email = document.querySelector(".email");
let password = document.querySelector(".password");
if(email.value == storedEmail && password.value == storedPw){
alert("You are logged in")
}
else{
alert("Email or Password is incorrect please check and try again.")
}
}
}
HTML 2 - main.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../css/main.css" />
<script src="../js/main.js" type="module"></script>
<title>Register</title>
</head>
<body>
<main>
<div class="heading">
<h1>User Registration</h1>
</div>
<form action="../index.html" class="form-container">
<ul>
<li><label for="name">Name</label>
<input class="name" type="text" name="name" required />
</li>
<li><label for="surname">Surname</label>
<input class="surname" type="text" name="surname" required />
</li>
<li><label for="phone">Phone</label>
<input class="phone" type="text" name="phone" />
</li>
<li><label for="email">Email</label>
<input class="email" type="text" name="email" required /></li>
<li><label for="password">Password</label>
<input class="password" type="text" name="password" required /></li>
<button class="reg">Register</button>
</ul>
</form>
</main>
</body>
</html>
main.js
let registration = document.querySelector(".reg");
registration.addEventListener("click", validate);
export function validate() {
//get html elements
const formEl = {
id: createId(),
name: document.querySelector(".name").value,
surname: document.querySelector(".surname").value,
phone: document.querySelector(".phone").value,
email: document.querySelector(".email").value,
password: document.querySelector(".password").value,
};
let name = formEl.name;
let surname = formEl.surname;
let email = formEl.email;
let password = formEl.password;
if (!name) {
alert("Please fill in name");
}
if (!surname) {
alert("Please fill in Surname");
}
if (!email) {
alert("Please fill in email");
}
if (!password) {
alert("Please create a password");
}
usersArray.push(formEl);
store();
return formEl;
}
This error I get in the HTML 1 page
for some reason, it is preventing the sign-in function from executing. I am doing it this way for practice purposes, I know local storage is not the best method for this, but I am getting used to how local storage works.

Uncaught TypeError: Cannot read properties of undefined (reading 'uname') and also No debugger available, can not send 'variables'

Here I'm trying to execute the following code but it throws the above error in console log in website page, I am unable to identify the error .
I have coded this webpage in such a way that it should show an error like "enter the user name" and "enter the password" whenever the input boxes are left empty but instead of this it is showing an uncaught type error. Kindly help me to find the solution.
my github code link is:https://github.com/harish-123445/login-form-using-html-css-javascript
function vfun(){
var uname=document.forms["myform"]["uname"].value;
var pword=document.forms["myform"]["pword"].value;
if(uname==null || uname=="" ){
document.getElementById("errorBox").innerHTML =
"enter the user name";
return false;
}
if(pword==null || pword==""){
document.getElementById("errorBox").innerHTML =
"enter the password";
return false;
}
if (uname != '' && pword != '' ){
alert("Login successfully");
}
}
<!DOCTYPE html>
<html >
<head>
<title>sign in form</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="js.js"></script>
<body>
<div class="box">
<img src="user.png" class="user">
<h1 >LOGIN HERE</h1>
<form class="myform" onsubmit= "return vfun()">
<p>USERNAME </p>
<input type="text" name="uname" placeholder="enter username" >
<p>PASSWORD </p>
<input type="password" name="pword" placeholder="enter password">
<div id="errorBox"></div>
<input type="submit" name="" value="login">
<br><br>
<a href="register.html" >Register for new user</a>
</form>
</div>
</body>
</head>
</html>
I have edited your code. I have called your username and password using getElementById and your two error boxes with different id names and now it is working fine.
function vfun(){
var uname=document.getElementById("name").value;
var psword=document.getElementById("passw").value;
if(uname==null || uname=="" ){
document.getElementById("errorBox2").innerHTML =
"enter the user name";
return false;
}
if(psword==null || psword==""){
document.getElementById("errorBox").innerHTML =
"enter the password";
return false;
}
if (uname != '' && pword != '' ){
alert("Login successfully");
}
}
<!DOCTYPE html>
<html >
<head>
<title>sign in form</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="js.js"></script>
<body>
<div class="box">
<img src="user.png" class="user">
<h1 >LOGIN HERE</h1>
<form class="myform" onsubmit= "return vfun()">
<p>USERNAME </p>
<input type="text" name="uname" id="name"
placeholder="enter username" >
<div id="errorBox2"></div>
<p>PASSWORD </p>
<input type="password" name="pword" id="passw"
placeholder="enter password">
<div id="errorBox"></div>
<input type="submit" name="" value="login">
<br><br>
<a href="register.html" >Register for new user</a>
</form>
</div>
</body>
</head>
</html>

Retrieve and show DATA FORMS (GET) in Javascript

I have a first page, which, onload, shows the default get params.
Page1.html
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script defer src="assets/main.js"></script>
<title>Document</title>
</head>
<body">
<div>
<h1>Nous avons reçu : </h1>
<h2 style="display: inline-block">LOGIN : </h2>
<p style="display: inline-block" id="login"></p>
</div>
<div >
<h2 style="display: inline-block">PASSWORD : </h2>
<p style="display: inline-block" id="password"></p>
</div>
</body>
<script>
</script>
</html>
Page1_main.js
// Version 1
const url = new URL(window.location.href);
const params = url.searchParams;
params.set('LOGIN', 'Licois');
params.append('PASSWORD', 'Johanne')
url.search = params.toString();
window.history.replaceState({}, '', location.pathname + '?' + params);
if (params.has('LOGIN')) {
alert("Licois !");
} else {
alert("Licois est introuvable !")
}
if (params.has('PASSWORD')) {
alert("Johanne !");
} else {
alert("Johanne a disparu !")
}
document.getElementById("login").innerHTML = params.get("LOGIN");
document.getElementById("password").textContent = params.get("PASSWORD");
Result : page1 result
Ok, this is what I wanted.
But then, I have to have another page (with html only), which will send new get parametes to the first page, and shown them there in the HTML and URL. But in this case I cannot show "Joanne" and "Licois" anymore, or show the new params as "param3= " and "param4= ".
Page2_html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercice 2</title>
</head>
<body>
<form action="Page1.html" method="GET">
<label for="login">Login</label>
<input type="text" name="login" id="login" >
<div><br></div>
<label for="password">Password</label>
<input type="text" type="password" for="password" name="password" id="password">
<div><br></div>
<button type="submit" id="envoyer">Envoyer</button>
</form>
</body>
</html>
Page2_form
I succeed at sending the new params to the first page ("action='Page1.html'").
But I can't manage to show them in the HTML and URL.
No, nevermind, I got it.
Changed Page2.html to
<body>
<form action="Page1.html" method="GET">
<label for="login">Login</label>
<input type="text" name="NEW_LOGIN" id="NEW_LOGIN" >
<div><br></div>
<label for="password">Password</label>
<input type="text" type="password" for="password" name="NEW_PASSWORD" id="NEW_PASSWORD">
<div><br></div>
<button type="submit" id="envoyer">Envoyer</button>
</form>
</body>
</html>
And added this to Page1_main.js
if (params.has('NEW_LOGIN')) {
document.getElementById("login").innerHTML = params.get("NEW_LOGIN");
} else if ((params.has('LOGIN'))) {
document.getElementById("login").innerHTML = params.get("LOGIN");
}
if (params.has('NEW_PASSWORD')) {
document.getElementById("password").innerHTML = params.get("NEW_PASSWORD");
} else if ((params.has('PASSWORD'))) {
document.getElementById("password").innerHTML = params.get("PASSWORD");
}
EZ

Cannot set property 'innerHTML' of null at validation at HTMLInputElement.onkeydown

I was making simple contact form with email validation, but I ran into an error in my JS code. I was trying to figure out how to fix it but I have no idea what to do.
I was also trying different solutions from other People on StackOverflow but nothing work.
This Is My HTML code :
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/style.css">
<title>blackbubble | Contact</title>
</head>
<body>
<form action="#" id="form">
<div class="form_body">
<div class="form_title">
<span></span>
<h1>Get In Touch</h1>
<span></span>
</div>
<div class="user_name">
<input type="name" placeholder="Your name"></input>
<input type="name" placeholder="Second name">
</div>
<div class="email">
<input type="email" id="email" placeholder="Your email address" onkeydown="validation()">
<p class="text"></p>
</div>
<div class="textarea_box">
<textarea placeholder="Message"></textarea>
</div>
<div class="form_footer">
<button class="btn btn_submit">Submit</button>
</div>
</div>
</form>
<script src="../assets/js/main.js"></script>
</body>
</html>
here is my JS Code:
function validation() {
var form = document.getElementById("form");
var email = document.getElementById("email").value;
var text = document.getElementById("text");
var text = document.getElementById("text");
var pattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (email.match(pattern)) {
form.classList.add("valid");
form.classList.remove("invalid");
text.innerHTML = "Your Email Address Is Valid.";
text.style.color = "#00ff00";
}
else {
form.classList.remove("valid");
form.classList.add("invalid");
text.innerHTML = "Please Enter A Valid Email Address.";
text.style.color = "#ff0000";
}
}
There is no element with the id text.
You probably meant to select the element with the class text instead. This can be done with document.querySelector() and the .text CSS selector.
function validation() {
var form = document.getElementById("form");
var email = document.getElementById("email").value;
var text = document.querySelector(".text");
var pattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (email.match(pattern)) {
form.classList.add("valid");
form.classList.remove("invalid");
text.innerHTML = "Your Email Address Is Valid.";
text.style.color = "#00ff00";
} else {
form.classList.remove("valid");
form.classList.add("invalid");
text.innerHTML = "Please Enter A Valid Email Address.";
text.style.color = "#ff0000";
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/style.css">
<title>blackbubble | Contact</title>
</head>
<body>
<form action="#" id="form">
<div class="form_body">
<div class="form_title">
<span></span>
<h1>Get In Touch</h1>
<span></span>
</div>
<div class="user_name">
<input type="name" placeholder="Your name">
<input type="name" placeholder="Second name">
</div>
<div class="email">
<input type="email" id="email" placeholder="Your email address" onkeydown="validation()">
<p class="text"></p>
</div>
<div class="textarea_box">
<textarea placeholder="Message"></textarea>
</div>
<div class="form_footer">
<button class="btn btn_submit">Submit</button>
</div>
</div>
</form>
</body>
</html>

Categories