onClick function doesn't work on first submit click - javascript

I'm new to javascript and need some help lol. I have done a form that is supposed to disappear onClick and be replaced with a text. It works... but only after the second time I click submit. How do I make it work the first time?
<div class="subscribe" id="subscribe">
<h1>SUBSCRIBE</h2>
<p>Be in the know and sign up for our email list.</p>
<form class="form" id="form">
<input type="text" id="fname" name="fname" placeholder="First Name" required>
<input type="text" id="lname" name="lname" placeholder="Last Name" required>
<input type="email" id="email" placeholder="Email" required>
<input type="submit" id="submit" onClick="replaceForm()">
</form>
</div>
<div id="replacement">
<p>Thank you for signing up!</p>
</div>
//in js file
function replaceForm() {
var form = document.getElementById("form");
form.style.display = 'none';
document.getElementById("replacement").style.display = "block";
}

Pass the implicit event object into replaceForm and then call e.preventDefault().
Also, consider using form.hidden = true; instead of form.style.display = 'none';.
Like so:
<input type="submit" id="submit" onclick="replaceForm(event)">
function replaceForm(e) {
e.preventDefault();
const form = document.getElementById("form");
form.hidden = true;
document.getElementById("replacement").style.display = "block";
}

Submit is use to submit your form data to particular URL, which get the data from form and process it further.
i.e example : login page - after adding user name password your are sending it to backend to process the user login credential.
In this code snippet you are not submitting data to any location so better you use button as input type.
Once you click on submit it send data to action location but in you have not mention action location so it will simple refresh the page with same URL.
<input type="button" id="submit" onClick="replaceForm()"/ >
HTML :
<div class="subscribe" id="subscribe">
<h1>SUBSCRIBE</h2>
<p>Be in the know and sign up for our email list.</p>
<form class="form" id="form">
<input type="text" id="fname" name="fname" placeholder="First Name" required>
<input type="text" id="lname" name="lname" placeholder="Last Name" required>
<input type="email" id="email" placeholder="Email" required>
<input type="button" id="submit" onClick="replaceForm()">
</form>
</div>
<div id="replacement">
<p>Thank you for signing up!</p>
</div>
function replaceForm() {
var form = document.getElementById("form");
form.style.display = 'none';
document.getElementById("replacement").style.display = "block";
}

Related

Error message will not display after changing the type for a button in form

So I am trying to add validation to a form. Initially, for the button, I had the type as submit, but when I would click on the button the error message for an empty name input would display briefly. I did some research and saw that in order to get the error message to display longer, I needed to change the type to button, which I did. Now, no error messages are showing. I checked the console and there are no errors displaying. Can someone tell me why this is happening and how to fix it?
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
var name = document.regForm.FullName.value;
var nameError = true;
if (name == "") {
printError("nameError", "Please enter your name")
}
};
.error {
color: red;
font-size: 90%;
}
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm()">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<div class="error" id="nameError"></div>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<div class="error" id="emailError"></div>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
</div>
<span id="Message"></span>
<button type="button" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
When the button type is submit the form gets submitted automatically and the function called validation is executed. But when you change the type to button the function will not be called. You have to add click event listener to the sign me up button to call the validate function.
jsFiddle

How to get a thank you after the completion of the form?

So, I am trying to get a "thank you" message instead of a form that I have created on HTML. I want to get a thank you message only if the user has submitted all their details and everything.
Here's my HTML:
<div class = "form">
<form>
<!-- Name -->
<label class = "firstName">First name</label><br>
<input type="text" placeholder = "John" required = "required" pattern="[A-Za-z]. {1,20}" id = "firstName"><br>
<label class = "lastName">Last name</label><br>
<input type="text" placeholder = "AppleSeed" required = "required" pattern="[A-Za-z]{1,20}" id = "lastName"><br>
<!-- Email -->
<label class = "email">Email</label><br>
<input type= "email" placeholder = "j.appleseed#example.co.uk" size = "42" required = "required" id = "email"><br>
<!-- Mobile Number -->
<label class = "tel">Mobile Number</label><br>
<input placeholder = "Your Mobile Number" size = "42" required = "required" pattern="[0-9]{6,13}" id = "number"><br><br>
<!-- The Submit button -->
<button class = "submit" onclick="revealMessage()">
<span title="What are you waiting for? Click it!">Submit</span>
</button>
<h1 id = "hiddenMessage" style = "display: none">Thank You!</h1>
</form>
</div>
Javascript:
function revealMessage()
{
document.getElementById("hiddenMessage").style.display = "block";
document.getElementsByClassName("form").style.display = "none";
}
getElementsByClassName is plural. You need to add [0] to the result or better, don't use it
You want to access the submit event - just hiding the form when clicking the button, will not submit the form and also not trigger the validation
You had a bug in your pattern for the First name too
When you hide the form div, the content will hide too
You may want to use AJAX since the form removes the page when submitting - with Ajax you can return thank you from the server
Anyway this shows the thankyou before submitting when things are filled correctly. the HTML5 required and the pattern will not allow submission until correctly filled
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // pause submission
document.getElementById("hiddenMessage").style.display = "block";
document.getElementById("formDiv").style.display = "none";
setTimeout(function() {
e.target.submit()
}, 2000)
})
<div class="form" id="formDiv">
<form id="myForm">
<!-- Name -->
<label class="firstName">First name</label><br>
<input type="text" placeholder="John" required="required" pattern="[A-Za-z]{1,20}" id="firstName"><br>
<label class="lastName">Last name</label><br>
<input type="text" placeholder="AppleSeed" required="required" pattern="[A-Za-z]{1,20}" id="lastName"><br>
<!-- Email -->
<label class="email">Email</label><br>
<input type="email" placeholder="j.appleseed#example.co.uk" size="42" required="required" id="email"><br>
<!-- Mobile Number -->
<label class="tel">Mobile Number</label><br>
<input placeholder="Your Mobile Number" size="42" required="required" pattern="[0-9]{6,13}" id="number"><br><br>
<!-- The Submit button -->
<button type="submit" class="submit">
<span title="What are you waiting for? Click it!">Submit</span>
</button>
</form>
</div>
<h1 id="hiddenMessage" style="display: none">Thank You!</h1>
Instead of:
document.getElementsByClassName("form").style.display = "none";
Use querySelector:
document.querySelector(".form").style.display = "none";
Also, move your hiddenMessage div outside of your form so it doesn't get hidden with the form on submit.
See the snippet below:
function revealMessage() {
document.getElementById("hiddenMessage").style.display = "block";
document.querySelector(".form").style.display = "none";
}
<div class="form">
<form onsubmit="revealMessage()">
<!-- Name -->
<label class="firstName">First name</label><br>
<input type="text" placeholder="John" pattern="[A-Za-z]. {1,20}" id="firstName" required><br>
<label class="lastName">Last name</label><br>
<input type="text" placeholder="AppleSeed" pattern="[A-Za-z]{1,20}" id="lastName" required><br>
<!-- Email -->
<label class="email">Email</label><br>
<input type="email" placeholder="j.appleseed#example.co.uk" size="42" id="email" required><br>
<!-- Mobile Number -->
<label class="tel">Mobile Number</label><br>
<input placeholder="Your Mobile Number" size="42" pattern="[0-9]{6,13}" id="number" required><br><br>
<!-- The Submit button -->
<button type="submit" class="submit">
<span title="What are you waiting for? Click it!">Submit</span>
</button>
</form>
</div>
<h1 id="hiddenMessage" style="display: none">Thank You!</h1>
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onsubmit
There is an event Called onsubmit on javascript when you submit you can alert or do what ever suits you
<div class="form">
<form onsubmit="myFunction()">
<!-- Name -->
<label class="firstName">First name</label><br>
<input type="text" placeholder="John" required="required" id="firstName"><br>
<label class="lastName">Last name</label><br>
<input type="text" placeholder="AppleSeed" required="required" pattern="[A-Za-z]{1,20}" id="lastName"><br>
<!-- Email -->
<label class="email">Email</label><br>
<input type="email" placeholder="j.appleseed#example.co.uk" size="42" required="required" id="email"><br>
<!-- Mobile Number -->
<label class="tel">Mobile Number</label><br>
<input placeholder="Your Mobile Number" size="42" required="required" id="number"><br><br>
<!-- The Submit button -->
<button class="submit">
<span title="What are you waiting for? Click it!">Submit</span>
</button>
</form>
</div>
<h1 id="hiddenMessage" style="display: none">Thank You!</h1>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>

onsubmit form validation. Form submits even though there are errors

I created a registration page, and each field requires entry and validation. I used the onsubmit event to call my js function to validate the form if the field is empty, however it still submits even though it has not been validated properly.
function validate() {
var streetName = document.getElementById("sN").value;
if (streetName == "" || streetName == null || streetName == undefined) {
window.alert("Sorry");
return false;
}
}
<form name="myForms" action="https://httpbin.org/post " method="post" class="form" onsubmit="return validate()">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" required>
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" required="">
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
// Somemore inputs
<input class="buttons" type="submit" name="submit" value="Sign up" onclick="validate()">
</form>
I expect a window to pop up saying "this entry is wrong and for this reason", but it submits anyway
EDIT: I apologize I should've been clearer in my post. I will use required in some of the inputs, however I will eventually need to write js code to ensure a phone number is all digits and password = passwordconfirm and a postal code is an actual postal code. In the JS file I just showed what I basically tried doing.
Several things
You have validate on the submit AND on the form submit
You should NEVER call anything in a form "submit" since it will hide the submit event/method
You need to get the correct field
Give the form an ID and use unobtrusive code like this
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var errors = false;
var streetName = this.streetname.value.trim(); // no more action needed
if (!streetName) errors = true;
// more validations
if (errors) {
window.alert("Sorry");
e.preventDefault();
}
});
});
<form id="myForm" action="https://httpbin.org/post " method="post" class="form">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" >
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" >
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
<input class="buttons" type="submit" name="SubmitButton" value="Sign up">
</form>
var streetName = document.getElementById("sN").value;
There is no element with that id in the document.
There is an element with sN as its class name, but getElementById won't find an element by its class and the value of <div class="sN"> will always be undefined. It is the input that will have a value.

image onclick() function to display dailog window with form details

Hers is the code i written for functionality , when click on image, dailog window should load with form input elements. Please look into the below code and let me know where i did mistake.
code:-
<dialog id="login" style="border-color: blue; border: 1px solid">
<form name="reg">
First Name : <input type="text" name="fname" required>
Last Name: <input type="text" name="lname" required>
Email <input type="email" name="mail" required>
Password: <input type="password" name="pass" required>
Confirm Password : <input type="password" name="confpass" required>
<button type="submit"></button>
<button type="reset"></button>
</form>
</dialog>
<script>
function registration(){
var dailog = document.getElementById('login');
dailog.open();
}
</script>
According to MDN there are .show() and .showModal() methods - there's no .open() method.
Change
dailog.open();
to
dailog.open = true;
as
show
is property, not a function

Calling a javascript function in html

I'm working on javascript and html. I have a javascript function, called login, and I want to call this function in HTML. I saw some codes that includes the javascript function directly in the HTML. I don't want to do it because the code is very long.
Here is the HTML:
<input class="form-control form-stacked" name="username" placeholder="Username" type="text" required="true" id="username">
<input class="form-control form-stacked last" name="password" placeholder="Password" type="password" required="true" id="password">
<script>
window.onload = login()
</script>
<input class="btn btn-beats btn-block btn-stacked" value="Tune in" type="submit">
And the Javascript function is:
function login(){
var userName = document.getElementById("username").value;
var password = document.getElementById("password").value;
console.log(userName);
console.log(password);
var data = {
userName : userName,
password : password
};
console.log(data);
doJSONRequest("POST", "/login", {}, data, function(location){
document.location = location.location;
});
}
I included a window.onload because I want to call the function when the page started. The console (obliviously) says to me that "login in not defined" and, of course, it has reason. But I don't want to put all the code into the HTML (also because there are like 30 lines more). Can you help me please? Thanks to everyone :)
I think that what you want is to run your login code when the user clicks on the button. You can do that this way:
<form>
<input class="form-control form-stacked" name="username" placeholder="Username" type="text" required="true" id="username">
<input class="form-control form-stacked last" name="password" placeholder="Password" type="password" required="true" id="password">
<input class="btn btn-beats btn-block btn-stacked" value="Tune in" onclick="login()">
</form>
<script src="login.js></script>
login.js:
function login(){
var userName = document.getElementById("username").value;
var password = document.getElementById("password").value;
console.log(userName);
console.log(password);
var data = {
userName : userName,
password : password
};
console.log(data);
doJSONRequest("POST", "/login", {}, data, function(location){
...
});
Put the javascript in another js file(eg: filename.js) and load it load it in the header..
<script src="path to the file"></script>
Also you have to change window.onload = login() to window.onload = login
window.onload expects a reference of a function. When you use window.onload = login() the return value of the login() function is set as the reference which is not correct. The function name login is the reference..
SOLUTION
Just to be correct with the other users here is my solution:
<form action="login.html" method="POST" class="form-signup">
<input class="form-control form-stacked" name="firstname" placeholder="Firstname" type="text" required="true">
<input class="form-control form-stacked" name="lastname" placeholder="Lastname" type="text" required="true">
<input class="form-control form-stacked" name="username" placeholder="Username" type="text" required="true" id="username" onkeyup="login()">
<input class="form-control form-stacked" name="email" placeholder="email" type="email" required="true">
<input class="form-control form-stacked" name="password" id = "password" placeholder="Password" type="password" required="true" onkeyup="login()">
<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password" onkeyup="enable()" required="true">
<input class="btn btn-beats btn-block btn-stacked" value="Sign up" id = "btnPlaceOrder" type="submit">
</form>
I just add the function "login" when the user wants to store the values

Categories