Javascript not working for the first time when webpage open? - javascript

I am working on a project where I need to send my data to the firebase of the form.
Link - http://ietvit.com/hackoff/
Github repo link - https://github.com/vivanks/hackoffproject
But on filling out the form it should pop up alert window and submit the form but when I open the website for the first time it does not do anything when it refreshes instead it starts to work perfectly but not for the first time. Any reason why or any suggestions to prevent.
Example :
I open my website for the first time and fills out the subscribe form but it just simply refreshes the page instead of updating firebase and pop-ing alert window.
My html form -
<form class="contact100-form validate-form">
<div class="wrap-input100 m-b-10 validate-input" data-validate = "Name is required">
<input id="name" class="s2-txt1 placeholder0 input100" type="text" name="name" placeholder="Your Name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 m-b-20 validate-input" data-validate = "Email is required: ex#abc.xyz">
<input id="email" class="s2-txt1 placeholder0 input100" type="text" name="email" placeholder="Email Address">
<span class="focus-input100"></span>
</div>
<div class="w-full">
<p class="s2-txt3 p-t-18">
And don’t worry, we hate spam too! You can unsubcribe at anytime.
</p><br>
<button id="submitBtn" onclick="submitDetail()" name="submit" class="flex-c-m s2-txt2 size4 bg1 bor1 hov1 trans-04">
Submit
</button>
</div>
</form>
My java script -
var nameText = document.getElementById("name");
var emailText = document.getElementById("email");
var submitBtn = document.getElementById("submitBtn");
const firebaseRef = firebase.database().ref();
function submitDetail(){
var nText = nameText.value;
var eText = emailText.value;
firebaseRef.push().set({
name : nText,
email : eText
});
window.alert("Subscribed Successfully")
}

<div class="wrap-input100 m-b-20 validate-input" data-validate = "Email is required: ex#abc.xyz">
<input id="email" class="s2-txt1 placeholder0 input100" type="text" name="email" placeholder="Email Address">
<span class="focus-input100"></span>
</div>
<div class="w-full">
<p class="s2-txt3 p-t-18">
And don’t worry, we hate spam too! You can unsubcribe at anytime.
</p><br>
<button id="submitBtn" onclick="submitDetail(event)" type="submit" name="submit" class="flex-c-m s2-txt2 size4 bg1 bor1 hov1 trans-04">
Submit
</button>
</div>
</form>
And in js to prevent reload :
function submitDetail(ev){
ev.preventDefault();
var nText = nameText.value;
var eText = emailText.value;
firebaseRef.push().set({
name : nText,
email : eText
});
window.alert("Subscribed Successfully")
}

Related

Want to do local storage with login details

Currently, I am trying to store the email and password that is entered. Below I have the HTML and JS code
let email = document.querySelector(".email");
let password = document.querySelector(".password");
//Storing users email and password
function store()
{
localStorage.setItem('email',email.value)
localStorage.setItem('password', password.value)
}
function checkLogin()
{
//get set stored data
let emailStored = localStorage.getItem('email')
let passwordStored = localStorage.getItem('password')
//data entered from login-form
let emailInput = document.querySelector('.email').value
let passwordInput = document.querySelector('.password').value
if(emailInput != emailStored)
{
let eError = document.querySelector(".email-error-message")
eError.innerHTML = "Please enter valid email address"
}
if(passwordInput != passwordStored)
{
let pError = document.querySelector(".password-error-message")
pError.innerHTML = "Please enter password associated with email address"
}
}
<div class="login-form">
<div class="sign-in">
<h1>Sign In</h1>
<form class="form">
<input class="email" type="email" placeholder="Email Address" required />
<div class="email-error-message"></div>
<input class="password" type="password" placeholder="Password" minlength="6" required />
<div class="password-error-message"></div>
<button class="submit">Sign In</button>
<div class="remember-me">
<input class="checkbox" type="checkbox" />
<span class="remember">Remember me</span>
<span class="need">Need help?</span>
</div>
</form>
<div class="facebook-signin">
<img src="images/facebook_social media_social_icon.png" alt="facebook logo" />
<span class="flogin">Login in with facebook</span>
</div>
<div class="newNetoflix">
<div class="newToNetflix">New to Netflix?</div>
<a class="sign-up" data-uia="login-signup-now">Sign up now.</a>
</div>
<div class="disclaimer">
<span class="protected">This page is protected by Google reCAPTCHA to ensure you're not a
bot. </span>
<button type="submit" class="learn-more">Learn More</button>
</div>
</div>
</div>
My end goal is the following:
when the user inputs their email address and password it is saved
when user clicks the check box of remember me it keeps their email address there, but not their password.
PS: I am aware there needs to be an event listener with the checkbox, saying that when the checkbox is checked keep email when the browser refreshes.

Redirect to another HTML page after successfull login attempt | with JS

I have created a login form. I want a JS code that:
If the information on the login page i.e Username and Login is correct, It will proceed to another HTML page.
Simply, I want the page to redirect to another page after successfull login attempt. | With JS
I dont want any PHP or MySql code.
I have tried this code but this doesnt works. On wrong information, it says Invalid information. But on correct info, it refreshes the page and there a ? is visible at te end of the url:
Html:
<form id="form" action="" method="GET">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" id="email" class="form-control" aria-describedby="emailHelp" >
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit" class="btn btn-outline-success btn-lg shadow" onClick="auth()">Submit</button>
</form>
JavaScript:
function auth() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
location = location['href'];
// alert("You Are a ADMIN");
} else {
alert("Invalid information");
return;
}
}
I have also used:
window.location.replace("upload.html");
instead of:
location = location['href'];
But still does not works.
A couple of things here. One you're doing a GET with your form rather than doing a POST. You should change that. Second, on your JavaScript call for auth you should pass the event parameter so that the default action of the form will be stopped. Third, you should be using a relative path for your URL within your redirect. Last, You should do a window.redirect() to simulate an HTTP redirect when the function executes.
Here is the code with the updates:
<form id="form" action="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email"
id="email"
class="form-control"
aria-describedby="emailHelp" >
<small id="emailHelp"
class="form-text text-muted">
We'll never share your email with anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit"
class="btn btn-outline-success btn-lg shadow"
onClick="auth(event)">Submit</button>
</form>
<script>
function auth(event) {
event.preventDefault();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
window.location.replace("/upload.html");
} else {
alert("Invalid information");
return;
}
}
</script>

function not pulling input data from local host

I am creating a simple login an sign up form that is used to create a user and store it in the local host. I have got the sign up form working as it should, but when I try and pull the information from the localhost, it just refreshes the page. Im just wondering how I can get the function to work correctly.
Here is my JS:
const signup = (e) => {
let user = {
firstName: document.getElementById("firstName").value,
lastname: document.getElementById("lastName").value,
email: document.getElementById("email").value,
username: document.getElementById("username").value,
password: document.getElementById("password").value,
confirm_password: document.getElementById("confirm_password").value,
};
localStorage.setItem("user", JSON.stringify(user));
console.log(localStorage.getItem("user"));
e.preventDefault();
alert("Signup Successful")
};
function login() {
var stored_username = localStorage.getItem('username');
var stored_password = localStorage.getItem('password');
var username1 = document.getElementById('username1');
var password2 = document.getElementById('password2');
if(username1.value == stored_username && password2.value == stored_password) {
alert('Login Successful.');
}else {
alert('Username or password is incorrect.');
}
}
document.getElementById("login-btn").addEventListener(type = click, login())
And here is my HTML:
<div class="bodyBx">
<section>
<div class="container">
<div class="user signinBx">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1551034549-befb91b260e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form>
<h2>Sign In</h2>
<input type="text" id="username2" placeholder="Username" />
<input type="password" id="password2" placeholder="Password" />
<button id = "login-btn" type="submit" onclick="login();">Submit</button>
<p class="signup">
Need an account ?
Sign Up.
</p>
</form>
</div>
</div>
</div>
</section>
<!-- ================= Sign Up Form Start ================= -->
<section>
<div class="container">
<div class="user signupBx" id="section2">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1555680206-9bc5064689db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form role="form" onsubmit="signup(event)">
<h2>Sign Up</h2>
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<input type="email" id="email" placeholder="example#email.com..." />
<input type="text" id="username" placeholder="Username" />
<input type="password" id="password" placeholder="Password" />
<input type="password" id="confirm_password" placeholder="Confirm Password" />
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
</section>
</div>
Change the type of login button to button from submit, like below
<button id = "login-btn" type="button" onclick="login();">Submit</button>
If type=submit the form is posted to the url specified in the action attribute of the form, else to the same page if action is missing and you will see a page refresh.
Alternate method - You can also try return false; in your login()
Also your addEventListener should be like below, you don't have to provide type = click, the first param is of type string and second param is of type function. Check docs
document.getElementById("login-btn").addEventListener("click", login)
Localstorage can only store text. So you store a stringified object, which is fine, but you're trying to retrieve properties from it which don't exist.
Instead of:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
localStorage.getItem("someField");
//localstorage doesnt know what someField is
You want:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
itm = JSON.parse(localStorage.getItem("itm"));
someField = itm.someField
As for the refresh, check this out:
Stop form refreshing page on submit
TL;DR: Add e.preventDefault() in function login() (you'll have to change it to function login(e).

The $_POST unable to retrieve data from the text field in the html file

There is a discovery.html file that links to a validate_signup.php file through action in the html form. When in the I am in the validate_signup.php and try to retrieve the values with $_POST['XXX'] of the text fields in the form namely regFName, regSName, regEName, regPName it returns an error that states undefined index XXX.
File directory(not sure if it could play a part)
Folder-- HTML, PHP, ect
HTML-- discovery.html, ect
PHP-- validate_signup.php, ect
I create an other html and php file that works similarly and in this example it worked.
HTML FROM:
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" methode="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName"required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para" ></span>
</div>
</form>
PHP:
$password = $_POST["regPName"];
$email = $_POST["regEName"];
$surname = $_POST["regSName"];
$firstname = $_POST["regFName"];
JS-validate data
var error="";
var name = document.getElementById( "regFName" );
if(valPass() == false)
{
error = "Password must contain an UpperCase, LowerCase, Number and Symbol character";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
var email = document.getElementById( "regEName" );
if( email.value == "" || email.value.indexOf( "#" ) == -1 )
{
error = " You Have To Write Valid Email Address. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
else
{
return true;
}
the correct method not methode
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" method="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName" required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para"></span>
</div>
</form>

Pop-up messages during registration

recently started to deal with javascript, now I'm doing a registration page. And at the moment the notification about the incorrect filling of the form is displayed via alert (). How can this be improved so that if you enter incorrectly, you immediately see a hint ?
function valid(form){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker = "Wrong first name";
}else if(!namePattern.test(lName)){
checker = "Wrong last name"
}else if(!passwordPattern.test(password)){
checker = "Wrong password"
}else if(confirmPassword != password){
checker = "Your passwords do not match"
}else if(!emailPattern.test(email)){
checker = "Wrong email"
}
if(checker){
alert(checker);
}
}
<form action="" method="post" name="submit" onsubmit="valid(this)">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<input type="submit" name="submit" value="submit"/>
</form>
I will be grateful for help)
I suggest you put on input elements onchange function, for example:
<input type="text" name="fName" id="fName" placeholder="Your first name" onchange='validateInput(e)'>
And then you check in function:
function validateInput(e){
var namePattern = new RegExp("^([A-z]{4,20})$");
const value = e.target.value;
if(!namePattern.test(value)){
alert("Wrong first name");
// But instead of alert I would suggest you change the color of the input element in order for the user to see real time that he is entering wrong thing.
//When he enters correct data, input border should be green. This is much more user friendly
}
}
You can every validation check separately like this...
function firstname(value){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
if(!namePattern.test(value)){
checker = "Wrong first name";
}
if(checker){
alert(checker);
}
}
<input type="text" name="fName" id="fName" placeholder="Your first name" onblur="firstname(this.value)">
I suggest you can use jquery validation.
The thing is, you are checking your form on your submit event (which is obviously the event that is trigger when the form is submitted).
You need to add input validation on each of your input fields via certain event listeners.
If you add onchange event listener, your callback validation will fire each time you move your focus to another element (aka blur event).
If you add oninput event listener, your callback validation will fire each time you type something new.
I would recommend taking a look at the answers of this question.
var checker;
function valid(form){
checker = '';
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker += "No first name<br/>";
}
if(!namePattern.test(lName)){
checker += "No last name<br/>"
}
if(!passwordPattern.test(password)){
checker += "No password<br/>"
}
if(confirmPassword != password){
checker += "Your passwords do not match<br/>"
}
if(!emailPattern.test(email)){
checker += "No email<br/>"
}
if(checker){
document.getElementById("hint").innerHTML = checker;
}
}
valid(document.getElementById("form"));
<form id='form' action="return false;" method="post" name="submit" oninput="valid(this)" onsubmit=' return false;'>
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div style='color:red' id='hint'></div>
<input type='submit'/>
</form>
Using the oninput event to run every single time a input is changed. More user friendly by displaying a text tip instead of popups, and shows all errors, not just the first one in the if/elseif loop.
P.S: You seem to have forgotten to add the submit button in your code.
EDIT: Also made it check validation as soon as the page loaded up too.

Categories

Resources