Multiphase Form (wizard) show all information before submit - javascript

I create a multiphase form (wizards from) and I want to show in the last step all Information in input text (you can modify it) before validate
I try a lot but without any result, how can I do it ?
My code
var fname, lname, age;
function _(x) {
return document.getElementById(x);
}
function processPhase1(){
fname = _("firstname").value;
lname = _("lastname").value;
if(fname.length > 2 && lname.length > 2){
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
else {alert("Please Enter All Information");}
}
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
}
else {alert("Please Enter All Information");}
}
<body>
<div id="phase1">
First Name : <input id="firstname" name="firstname"><br>
Last Name : <input id="lastname" name="lastname"><br>
<button onclick="processPhase1()">Next</button>
</div>
<div id="phase2">
Age : <input id="age" name="age"><br>
<button onclick="processPhase2()">Next</button>
</div>
<div id="show_info">
First Name : <input id="firstname" name="firstname" value = ""><br>
Last Name : <input id="lastname" name="lastname" value = ""><br>
Age : <input id="age" name="age" value = ""><br>
<button onclick="submit()">submit</button>
</div>
I try this but it's just for showing Information, but you can't modify it, I need to show it in input text
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
_("display_fname").innerHTML = fname;
_("display_lname").innerHTML = lname;
_("display_age").innerHTML = age;
}
else {alert("Please Enter All Information");}
}
<div id="show_info">
First Name : <span id="display_fname"></span><br>
Last Name : <span id="display_lname"></span><br>
Age : <span id="display_age"></span><br>
<button onclick="submit()">submit</button>
</div>

I would have done this completely different, but this is how you would do it based on what you've already written. When you click the next button in each function, you want to grab that value of (fname, lname, or age) and set the value of that to the value of the last set of inputs. I've altered your code a bit and made you a JS BIN http://jsbin.com/sopikuzuri/edit?html,output
In simple terms
Each time you call a new phase function (processPhase1), you want to grab the values of what the user just entered.
Then, you want to set those values to the proper <input />
So, the simplest example I can give is this:
Below, the user will enter some data into the field. When they click the submit phase 1 button we will grab the value of what they just entered and set that value to the last input (for them to see/edit)
<input type="text" id="firstName"/>
<button id="submit">Submit Phase 1</button>
<input type="text" id="displayInput"/>
<script>
$("#submit").click(function() {
// getting the value of what the user typed in
var fname = $("#firstName").value;
// setting the value of the final box to the var above
$("#displayInput").val(fname);
});
</script>

Related

(Javascript) oninput with numbercheck

I'm trying to make a simple inventory systems. But I'm having problem with my oninput event.
I want to make TOTAL GOODS to be "Please input number in GOODS IN " whenever every non number value inserted into GOODS IN. But it seems I can't make it so.
/*MAKE EVERY TABLE CLICKABLE AND SHOW ROW DATA IN INPUT TEXT*/
var tbGoods = document.getElementById('tbGoods');
for (var i = 0; i < tbGoods.rows.length; i++) {
tbGoods.rows[i].onclick = function() {
document.getElementById("idTxt").value = this.cells[1].innerHTML;
document.getElementById("gdTxt").value = this.cells[2].innerHTML;
document.getElementById("qtyTXT").value = this.cells[3].innerHTML;
var qty = parseInt(document.getElementById('qtyTXT').value);
var x = parseInt(document.getElementById('gdin').value);
var result = qty - x;
document.getElementById('totalgd').value = result;
};
}
/*MAKE EVERY NUMBER I PUT IN GOODS IN, TO BE CALCULATED WITHOUT SUBMIT BUTTON (ONINPUT)*/
function testmin() {
var qty = parseInt(document.getElementById('qtyTXT').value);
var x = parseInt(document.getElementById('gdin').value);
var result = qty - x;
if (document.getElementById('gdin').value === '') {
document.getElementById('totalgd').value = '0';
} else if (document.getElementById('qtyTXT').value === '') {
document.getElementById('totalgd').value = '0';
} else if (Number.isNaN(document.getElementById('gdin').value)) {
document.getElementById('totalgd').value = 'Please Input Number in Goods In';
} else {
document.getElementById('totalgd').value = result;
}
}
<form method="post">
<label>ID</label>
<input type="text" name="id" id="idTxt" disabled>
<label>GOODS</label>
<input type="text" name="goods" id="gdTxt" disabled>
<label>AVAILABLE QTY</label>
<input type="text" name="qty" id="qtyTXT" disabled>
<label>GOODS IN</label>
<input type="text" name="gdin" id="gdin" oninput="testmin()">
<br>
<br>
<label>Total Goods</label>
<input type="text" name="totalgd" id="totalgd" value="0" disabled>
<br>
<input type="submit" name="submit" value="submit">
</form>
You don't need to code that manually. You can simply set the input type as "number" and your browser will not allow any non-numeric characters to be entered into the field.
Demo (run the snippet and try typing in the box):
<input type="number" id="gdin" name="gdin"/>
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number
Just add type = "number" in the input label for TOTAL GOODS. It should prevent user from entering any alphabet. Except "e"
<input type="number" name="totalgd" id="totalgd" value="0" disabled>
As pointed out, if you want to show an alert or something when an input of alphabet is there in TOTAL GOODS, you can just add
<input type="text" name="totalgd" id="totalgd" value="0" oninput = "checkFunction()" disabled>
and in the function you can check the input for :
function checkFunction() {
let totalGoodsIn = document.getElementById("totalgd").value;
let regExp = /[a-zA-Z]/g;
if(regExp.test(totalGoodsIn))
{
//logic if alphabet is present in TOTAL GOODS
}
else
{
//logic if alphabet is not present in TOTAL GOODS
}
}
if you want GOODS IN to be numeric just change the type of the label accordingly
function validateNumberField() {
var value = $("#numberField").val();
var pattern = /^\d+$/;
var isValid = pattern.test(value);
if(!isValid){
document.getElementById('totalgd').value = 'Please Input Number in Goods In';
}
}
<p>Please enter number :</p>
<input type="number" id="numberField" name="numberField"
oninput="validateNumberField()" />

Submit button clearing out form, and not displaying anything

I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)

How can I check if a variable is a specific type using javascript?

I'm a beginner in web development and I have an HTML form where a person can add his address , address number, region and postal code . In this form the address and the region have to contain only char letters .
(ex. Lakewood : correct Lakewood13 : error) . If any of these two variables contains a number I have to enter my data again to continue . Else, I move to the next page . I'm a complete beginner in javascript which I need to use to check my variable types and I would appreciate your help with guiding me to solve this problem .
This is my code with my HTML form with the address number and the region which are the variables we need in this problem :
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(typeof(a.value) === 'string'&&(typeof b.value) ==='string'){
//continue to next page(but how can I check if numbers are in the strings ?)
}
else{
//go back to form and enter again(how can I enter the elements again ? )
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs"> Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "checkdata()">Continue</button>
</form>
</div>
Thank you in advance .
You can try using regex to check if string contains any number in it:
if(!(/\d/.test(a.value)) && !(/\d/.test(b.value))){
Please Note: You also have to return false to prevent the default event if the condition is false and prefix return the function call in onclick attribute.
Demo:
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(!(/\d/.test(a.value)) && !(/\d/.test(r.value))){
alert('form submit');
}
else{
alert('no submit');
return false;
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs" Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "return checkdata()">Continue</button>
</form>
</div>
You can write a function for validity, then you can check for dependencies based on that **
function checkData() {
let adress = document.getElementById('address');
let region = document.getElementById('region');
function isValid(e) {
let isTrue;
for (let char in e) {
typeof e[char] !== 'string' ? alert('Please only type strings') : (isTrue = true);
}
return isTrue;
}
isValid(adress.value) && isValid(region.value) ? console.log('next page') : console.log('error');
}
checkData();
**
So need to check if the strings are containing numbers or not
hope you find more insight here: Check whether an input string contains a number in javascript
working demo :
// check if string contains number
function hasNumber(myString) {
return /\d/.test(myString);
}
function checkdata(e) {
e.preventDefault()
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
var isAddressContainsNumber = hasNumber(a.value);
var isRegionContainsNumber = hasNumber(r.value);
console.log(isAddressContainsNumber, isRegionContainsNumber)
if (isAddressContainsNumber === false && isRegionContainsNumber === false) {
console.log('None of string contains number')
} else {
console.log('One or Both string contains number')
}
}
const form = document.querySelector('.sign-form');
form.addEventListener('submit', checkdata);
<div class="form-area" id="forma">
<form class="sign-form">
<div class="form-container">
<h1> Enter purchase data below : </h1>
<label for "addrs" Address Name</label>
<input type="text" placeholder="Enter address name " id="address" name="addr" required/>
</label>
<label for "regn" > Region </label>
<input type="text" placeholder="Enter region " id="region" name="reg" required/>
</label>
</div>
<button type="submit" class="continuebtn">Continue</button>
</form>
</div>
I would recommend going through the string and getting the ASCII value of each character. Numbers 0-9 are ASCII characters 48-57. Javascript uses UTF-16 and the appropriate method (charCodeAt) returns a 16-bit UTF-16 value, but UTF-16 characters 0-127 match ASCII. So:
var testString = "abcd123";
var isValid = true;
for (var i=0;i<testString.length;i++)
{
if (testString.charCodeAt(i) > 47 && testString.charCodeAt(i) < 58)
{
isValid = false;
}
}
if (!isValid)
{
//Code here to alert the user
alert("There's a number in there!");
}
You are using typeof in wrong way, try this way
typeOf(variable you want to check)

how to validate input with javascript

I am trying to use the ErrorFoundFlag approach to Show an error message for all fields that are in error at once.
I have tried:
function processInfo() {
var errorFoundFlag = "N"; //Initialize variable to 'N'
firstName = $("firstname").value;
lastName = $("lastname").value;
numPets = $("numpets").value;
var message = "";
if (firstName >= 0) {
firstName = firstname.length;
msg += "Please enter first name";
errorFoundFlag = "Y";
}
if (lastName >= 0) {
lastName = lastname.length;
msg += "Please enter last name";
errorFoundFlag = "Y";
}
if (numPets >= 0) {
numPets = numpets.length;
msg += "Please enter the number of pets you have";
errorFoundFlag = "Y";
}
}
<p>
Enter First Name: <input type="text" id="firstname" />
<span id="firstname_error"></span>
</p>
<p>
Enter Last Name: <input type="text" id="lastname" />
<span id="lastname_error"></span>
</p>
<p>
How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1" />
<span id="numpets_error"></span>
</p>
I need the error message to appear next to the input boxes when no text is input. And when text is input, the error message should go away but it's not working for me.
for example:
if the
Enter First Name: is blank... (Please Enter First Name) Would Appear
but if the name is entered the error message should go away. and if the other two are blank but the first name is entered when they click submit there would be error messages showing for the ones left blank.
There are several issues, but making the minimum number of changes to get roughly what you're asking for could look something like the following.
First, to get the value with jQuery you'll want val() (instead of value): $("#firstname").val().
Then simple references to the error spans (for example: $("#firstname_error")). These are cleared every time so the errors go away.
Then comparing the values length to 0 (note this could still be buggy, for example, an empty space would pass: " ").
Then console logging the errorFoundFlag to do as you need.
Finally, calling this method on each input change with onchange.
There are a number of improvements that can be made, but these were the minimum number of changes to get what you had working.
function processInfo() {
var errorFoundFlag = "N"; //Initialize variable to 'N'
firstName = $("#firstname").val()
lastName = $("#lastname").val();
numPets = $("#numpets").val();
firstNameError = $("#firstname_error");
lastNameError = $("#lastname_error");
numPetsError = $("#numpets_error");
firstNameError.text("")
lastNameError.text("")
numPetsError.text("")
if (firstName.length === 0) {
firstNameError.text("Please enter first name");
errorFoundFlag = "Y";
}
if (lastName.length === 0) {
lastNameError.text("Please enter last name");
errorFoundFlag = "Y";
}
if (numPets.length === 0) {
numPetsError.text("Please enter the number of pets you have");
errorFoundFlag = "Y";
}
console.log(errorFoundFlag)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Enter First Name: <input type="text" id="firstname" onchange="processInfo()" />
<span id="firstname_error"></span>
</p>
<p>
Enter Last Name: <input type="text" id="lastname" onchange="processInfo()" />
<span id="lastname_error"></span>
</p>
<p>
How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1" onchange="processInfo()" />
<span id="numpets_error"></span>
</p>

Simple Age Verification in javascript

I'm a total Js noob and i'm trying to make a simple script to take values from two input tags and based on their value change a p tag. I'm probably just not using proper syntax but I can't find an answer online to how to do this.
The script is supposed to be like age verification for an r-rated movie. The first input is age and the second is whether or not the customer has an adult with them for if they are underage.
<pre>
<!DOCTYPE html>
<html>
<input type="text" id="age" value="your age">
<input type="text" id="adult" value="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
<script>
var age = document.getElementById("age").innerHTML;
var adult = document.getElementById("adult").innerHTML;
var result = document.getElementById("answer").innerHTML;
var oldEnough = false;
function checkAge(){
if(age.value >= 18){
oldEnough = true;
}
else{
oldEnough = false;
}
if(oldEnough == false){
if(adult.value == "y"){
result = "You are not old enough, but have an adult with you.";
}
else{
result = "You are not old enough and are unaccompanied."
}
}
else{
result = "You are old enough."
}
}
</script>
</html>
</pre>
Don't call .innerHTML on the input elements. Just set the variables to point to the elements.
When assigning the result, you need to use result.innerHTML at the time of the assignment. Assigning .innerHTML to the variable just copies the current contents of the element as a string, it doesn't make result a reference to the innerHTML property.
You should call parseInt on age, because .value is a string.
function checkAge() {
var age = document.getElementById("age");
var adult = document.getElementById("adult");
var oldEnough = false;
var result = document.getElementById("answer")
if (parseInt(age.value, 10) >= 18) {
oldEnough = true;
} else {
oldEnough = false;
}
if (oldEnough == false) {
if (adult.value == "y") {
result.innerHTML = "You are not old enough, but have an adult with you.";
} else {
result.innerHTML = "You are not old enough and are unaccompanied."
}
} else {
result.innerHTML = "You are old enough."
}
}
<input type="text" id="age" placeholder="your age">
<input type="text" id="adult" placeholder="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
The input elements can be more easily accessed if they are put in a form, and the logic can be simpler. Also, make sure you use appropriate elements and attributes, e.g. don't use value as a kind of placeholder, it should be a suitable default value (if there is one).
And don't use placeholders instead of labels, they should only be used as a hint for the kind of content required, they don't replace labels.
function checkAge(button) {
var form = button.form;
var result = document.getElementById("answer");
result.innerHTML = form.age.value >= 18? 'You are old enough.' :
form.adult.checked? 'You are not old enough, but have an adult with you.' :
'You are not old enough and are unaccompanied.';
}
<form>
<label>Age: <input type="text" name="age"></label>
<label>Adult: <input type="checkbox" name="adult"></label>
<input type="button" onclick="checkAge(this)" value="Check age">
<p id="answer"></p>
</form>

Categories