I have seen many different ways to do it, and any of them works me.
I am using bootstrap.
The form goes directly to the 'action' (I want to validate first on 'onupdate')
SCRIPT:
[...]
<!-- Bootstrap core CSS -->
<link href="../css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="../style.css" rel="stylesheet" type="text/css/">
<script type="text/javascript">
function valForm()
{
alert("HALOOOOOOOOO");
var errors = 0;
var title = document.forms["tutorial_form"]["title"].value;
var description = document.forms["tutorial_form"]["description"].value;
var url = document.forms["tutorial_form"]["url"].value;
if (title == null || title == "")
{
document.getElementById("title_div").style.class = "form-group has-warning";
errors++;
}
if (description == null || description == "")
{
document.getElementById("description_div").style.class = "form-group has-warning";
errors++;
}
if (url == null || url == "")
{
document.getElementById("url_div").style.class = "form-group has-warning";
errors++;
}
if( errors > 0)
{
document.getElementById("error_container").innerHTML = "<div class="alert alert-danger" role="alert"><p><b>ERROR!</b>All the information must be fulfilled.</p></div>";
return false;
}
}
</script>
</head>
FORM:
<div class="container">
<form name="tutorial_form" enctype="multipart/form-data" action="insert_tutorial.php" onsubmit="return valForm()" method="post">
<div id="title_div" class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title input">
</div>
<div id="description_div" class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" placeholder="Description" rows="5"></textarea>
</div>
<div id="url_div" class="form-group">
<label for="url">Video URL</label>
<input type="text" class="form-control" id="url" name="url" placeholder="Insert youtube url">
</div>
<div class="form-group">
<label for="file">Insert image file</label>
<input type="file" name="image" id="file">
<p class="help-block">Select the file. Take care that it's size is no longer that 16 MB.</p>
</div>
<input type="submit" value="Submit" name="submit" class="btn btn-success">
</form>
<hr>
</div>
Thank you in advance!!!
You have a syntax error in your last if statement, change the double quotes to single ones:
document.getElementById("error_container").innerHTML = "<div class='alert alert-danger' role='alert'><p><b>ERROR!</b>All the information must be fulfilled.</p></div>";
or you can escape them as well:
"<div class=\"alert alert-danger\" role=\"alert\"><p><b>ERROR!</b>All the information must be fulfilled.</p></div>";
Related
I have to make a registration page in a project that uses Django as the backend framework.. In the registration page, I have to input the names, email, password and mobile... During registration, I need to validate email if its a valid format, check if the mobile number is of 10 digits and check if the password is a strong one.. I want to do it using javascript... I have written the code for the form and also the javascript function... But while running on the server I am unable to get the desired validation checks and alerts... Please help what should i do?
signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
{% load static %}
<link rel="stylesheet" href="{% static 'signup1.css'%}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<!--Javascript form validator-->
<link rel="stylesheet" href="{% static './register.js' %}">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="text-center">
<h1>Signup</h1>
<h6>Register yourself</h6>
</div>
<form style="text-align: top;" name="myForm" method="POST" action="" onsubmit="validate()" >
{% csrf_token %}
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>First Name</b></label>
<input type="text" name="first_name"placeholder="First Name" class="form-control" id="name" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>Last Name</b></label>
<input type="text" name="last_name"placeholder="Last Name" class="form-control" id="name" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>Mobile Number</b></label>
<input type="tel" name="mobile" class="form-control" id="number" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>Email address</b></label>
<input type="email" name="email" placeholder="Enter Email Id" class="form-control" id="email" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label"><b>Password</b></label>
<input type="password" name="password" placeholder="Enter Password" class="form-control" id="password" required>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label"><b>Your Choice</b></label><br>
<input type="radio" id="user" name="user_type" value="user">
<label for="html">User</label><br>
<input type="radio" id="admin" name="user_type" value="admin">
<label for="css">Admin</label><br>
</div>
<button type="submit" class="btn btn-primary" onclick="validate()">Submit</button>
</form>
<a style="color: aqua; margin-top: 10px;" href="http://localhost:8000/"><small>Already Registered? Click to login</small></a>
</div>
</div>
</div>
</div>
</body>
</html>
register.js (In static folder of the project)
function validate()
{
var abc=document.forms["myForm"]["first_name"].value;
if(abc=="")
{
alert("Please enter the first name");
return false;
}
var def=document.forms["myForm"]["last_name"].value;
if(def=="")
{
alert("Please enter the last name");
return false;
}
var email = document.forms["myForm"]["email"].value;
var re = "/^[a-z0-9+_.-]+#[a-z0-9.-]+$"
var x=re.test(email);
if(x)
{}
else
{
alert("Email id not in correct format");
return false;
}
var mobile = document.forms["myForm"]["mobile"].value;
var check="^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$"
var a=check.test(mobile);
if(a)
{}
else
{
alert("Invalid mobile number");
return false;
}
var pass=document.forms["myForm"]["password"].value;
var checks="^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[#$!%?&])[A-Za-z\d#$!%?&]{8,}$"
var res=checks.test(pass);
if(res)
{}
else
{
alert("Password must contain atleast 1 small, 1 capital, 1 numeric, 1 special character and must be atleast 8 characters long");
return false;
}
}
Your regular expressions are formatted as strings, not regular expressions.
For example...
// re is string
var re = "/^[a-z0-9+_.-]+#[a-z0-9.-]+$"
var x=re.test(email);
// re is regex
var re = /^[a-z0-9+_.-]+#[a-z0-9.-]+$/
var x=re.test(email);
I have a simple form page, where there are several form validations. So far, the RESET button only clears the text field values.
But I need the validation messages to clear when the RESET button is pressed.
So far I have seen jQuery methods, but have no idea of implementing it as I am still learning.. Are there any other methods to do this without jQuery..?
Any help would be highly appreciated.
Here's my code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<script>
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
</script>
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
</html>
Don't reset them manual by repeating code. Define a custom reset function which iterates over error messages and empty all of them:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
Also don't put any script tag in your head tag. Read more here
Full code:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button onclick="validation(); return false;" class="btn btn-primary">Submit</button>
<button class="btn btn-secondary" onclick="resetForm(); return false;">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
<button type="reset" class="btn btn-secondary" onclick="clearErrors();">Reset</button>
function clearErrors() {
document.getElementById("emailMessage").innerHTML = "";
// ... repeat for other messages
}
You need to call the eraseText function separately like mentioned below
function eraseText() {
document.getElementById("fnameMessage").innerHTML = "";
document.getElementById("lnameMessage").innerHTML = "";
document.getElementById("emailMessage").innerHTML = "";
document.getElementById("phoneMessage").innerHTML = "";
}
<button onClick="eraseText()" type="reset" class="btn btn- secondary">Reset</button>
As the error/validation messages are displayed within span elements of the same class text-danger you can easily query the DOM using querySelectorAll to return a nodelist and then iterate through that collection and set the span text content to an empty string.
Note that I added a name to the form and used that name within the anonymous function in the event handler. With a name assigned to the form also means that you can identify elements simply by doing something like this:
const form=document.forms.enquiry;
const formFname=form.fname;
const formLname=form.lname;
etc etc
document.querySelector('button[type="reset"]').addEventListener('click',e=>{
e.preventDefault();
document.querySelectorAll('.text-danger').forEach(span=>span.textContent='')
document.forms.enquiry.reset()
})
function validation()
{
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if(formFname.length ==0)
{
document.getElementById("fnameMessage").innerHTML ="<em>You did not enter your first name</em>"
}
//Validate last name
if(formLname.length ==0)
{
document.getElementById("lnameMessage").innerHTML ="<em>You did not enter your last name</em>"
}
//Validate email
if(formEmail.length ==0)
{
document.getElementById("emailMessage").innerHTML ="<em>You did not enter your email</em>"
}
else
{
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(regex.test(formEmail)===false)
{
document.getElementById("emailMessage").innerHTML ="<em>Please enter a valid email</em>"
}
}
//Validate phone
if(formNumber.length ==0)
{
document.getElementById("phoneMessage").innerHTML ="<em>You did not enter your phone number</em>"
}
else if(formNumber.length !=10)
{
document.getElementById("phoneMessage").innerHTML ="<em>Phone Number must be exactly 10 digits</em>"
return false;
}
else
return true;
}
<div class="container">
<h2>General Enquiry Form</h2>
<form name='enquiry' method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname" >
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname" >
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email" >
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
take a look for my code
html code:
<div class="tech-news__search__container">
<div class="tech-news__search">
<input
id="subscribeInput"
type="text"
class="tech-news__search-input"
placeholder="example#gmail.com"
>
<button class="tech-news__search-button" id="subscribeButton">Subscribe</button>
</div>
<div class="resultBlock">
<p class="listOfSubscribers" id="listOfSubscribers"></p>
<div id="result"></div>
<div id="deleteAll"></div>
</div>
</div>
js code:
let node = null
let deleteAll
function renderItems() {
const items = getItem()
if (items.length) {
const listOfSubscribers = document.getElementById('listOfSubscribers')
listOfSubscribers.innerHTML = 'Subscribers'
items.map(item => {
node = document.createElement("LI");
let textnode = document.createTextNode(item);
node.appendChild(textnode);
document.getElementById("result").appendChild(node);
})
deleteAll = document.getElementById('deleteAll')
deleteAll.innerHTML = 'Delete All'
deleteAll.addEventListener('click', deleteItems)
}
}
renderItems()
function deleteItems() {
sessionStorage.removeItem('subscribers')
window.location.reload()
}
I have 3 inputs in html form.
I wrote html and copied js from another topic here. But I can't understand, what I need write down for working.
For example, I need after inserting data in input with id "tLogin" and clicking Enter moving focus on next input with id "tTable", and next move focus to input with id "tOrder". After entering data to tOrder return focus to tLogin.
function keyPressFunction(e) {
const focus = $(document.activeElement); //get your active elememt ie select input
let inputView;
if (e.which === 13 || e.keyCode === 13 ) {
inputView = focus.closest('div').next().find(".field-focus"); // go to tbody and search for next class name .field-focus
}
inputView.show().focus(); //focus and show next input in table
}
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<?!= include("index-css"); ?>
</head>
<body>
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Логин:" autofocus >
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Номер стола:" >
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name= "text" placeholder= "Заказ:" >
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
</body>
</html>
Thank you for help!
As Nitin mentions in the comment above, the Enter key is mainly used as a button press or submitting the form. Anyway, try this example for your solution.
const inputs = document.querySelector('.dws-input');
const formControl = document.querySelectorAll('.form-control');
formControl[0].focus();
function keyPressFunction(ev) {
if (ev.code !== 'Enter') return;
if (ev.target.value === '') return;
for (const i of formControl) {
if (i.value === '') {
i.nextElementSibling.focus();
break;
}
}
}
inputs.addEventListener('keydown', keyPressFunction);
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous" />
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name="username" placeholder="Логин:" autofocus />
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name="text" placeholder="Номер стола:" />
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name="text" placeholder="Заказ:" />
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
Please use this code.
const ids = $(":input").toArray().map(val => val.id);
$(":input").keypress(function keyPressFunction(e) {
const nextId = (ids.indexOf(document.activeElement.id) + 1) % ids.length;
if (e.which === 13 || e.keyCode === 13 ) {
document.getElementById(ids[nextId]).focus();
}
});
I have been creating a form where after I have input my values and submit, I want to show the data on another page
Here is my form:
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/checkout.css">
<p id="Header">Checkout page</p>
<div class="row">
<div class="col-75">
<div class="containeer">
{{!-- When fom submitted, transport to here --}}
<form id="form" action="receipt" style="checkout.css">
<div class="row">
<div class="col-50">
<h3>Billing Address</h3>
{{!-- Name --}}
<label for="name"><i class="fa fa-user"></i> Full Name*</label>
<input class="form-control" type="text" placeholder="Example: Chia Kai Jun" id="name" required />
<label for="email"><i class="fa fa-envelope"></i> Email*</label>
<input class="form-control" type="email" id="email" placeholder="Example: john#example.com" required />
<label for="adr"><i class="fa fa-address-card-o"></i> Address (Street, Block, Unit Number)*</label>
<input class="form-control" type="text" id="adr" name="address" placeholder="Example: Ang Mo Kio Street 69, Blk106P, #07-212" required />
<div class="row">
<div class="col-50">
<label for="zip">Zip*</label>
<input class="form-control"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
{{!-- Javascript code needed here to prevent using text --}}
pattern="\d*" maxlength="6" type="number" id="zip" name="zip" placeholder="Example: 123456" required />
</div>
</div>
</div>
<div class="col-50">
<h3>Payment</h3>
{{!-- Available credit cards to use with image --}}
<label for="fname">Accepted Cards</label>
<div class="icon-container">
<i class="fa fa-cc-visa" style="color:navy;"></i>
<i class="fa fa-cc-mastercard" style="color:red;"></i>
</div>
<label for="cname">Name on Card*</label>
<input class="form-control" type="text" id="cname" name="cardname" required />
<label for="ccnum">Credit card number*</label>
<input class="form-control" type="text" maxlength="19" id="ccnum" name="cardnumber" placeholder="Example: 1111-2222-3333-4444"required />
<div class="row">
<div class="col-50">
<label for="expyear">Exp Month and Year*</label>
<input class="form-control" type="month" id="expyear" name="expyear" required />
</div>
<div class="col-50">
<label for="cvv">CVV*</label>
<input class="form-control" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type="password" id="cvv" name="cvv" pattern="\d*" minlength="3" maxlength="3" required />
</div>
</div>
</div>
</div>
{{!-- Will link to thank you for purchase, but now link to base for testing --}}
<button type="submit" class="btn btn-primary" onclick="submitForm()">Submit</button><span id="hi">* - Must be filled in</span>
</div>
</div>
<div class="col-25">
<div class="container">
<h4>Cart <span class="price" style="color:black"><i class="fa fa-shopping-cart"></i></span></h4>
{{!-- Will be currently empty if nothing and have items if something there --}}
<p id="item">Thinkpad Laptop - $100</p>
<img class="card-img-top p-5" src="/images/laptop.png" id="laptopimage">
<hr>
<p id="price" value="$100">Total: $100 <span class="price" style="color:black"></span></p>
{{!-- Will display nothing if there are no items and will compute total cost if there are items --}}
</div>
</div>
</div>
</form>
<script>
function submitForm(){
let name = document.forms["form"]["name"].value;
let email = document.forms["form"]["email"].value;
let address = document.forms["form"]["address"].value;
let zip = document.forms["form"]["zip"].value;
let test = document.forms["form"]["test"].value;
if (name == "") and (email == "") and (address == "") and (zip == "") and (test == ""){
return false;
}
else if(typeof(localStorage) != "undefined"){
localStorage.name = document.getElementById("name").value;
localStorage.email = document.getElementById("email").value;
localStorage.adr = document.getElementById("adr").value;
localStorage.zip = document.getElementById("zip").value;
localStorage.test = document.getElementById("test").value;
}
document.getElementById("form").submit();
}
</script>
Here is where I show the data input:
.yeet{
font-size: 25px;
line-height: 200%;
padding: 40px;
}
.intro{
text-align: center;
}
</style>
<div class="intro">
<h1>Thank you for your purchase!</h1>
<h2>Please check that your checkout details are correct</h2>
</div>
<body onload="setData()">
<div class="yeet">
Name: <span id="name"></span><br>
Email: <span id="email"></span><br>
Address: <span id="adr"></span><br>
Zip: <span id="zip"></span><br>
Item: <span id="cvv"></span><br>
</div>
<script>
function setData(){
if(typeof(localStorage) != "undefined"){
document.getElementById("name").innerHTML = localStorage.name;
document.getElementById("email").innerHTML = localStorage.email;
document.getElementById("adr").innerHTML = localStorage.adr;
document.getElementById("zip").innerHTML = localStorage.zip;
document.getElementById("cvv").innerHTML = localStorage.cvv;
}
}
</script>
</body>
The values I want to show after the input is currently Name, Email, Address, ZIP and CVV. My CVV is giving me undefined when my other values are correct. I am not sure why
To set and get data from localStorage -
localStorage.setItem('variable_name', 'value');
localStorage.getItem('variable_name');
Please try to do this code.
<script>
function setData(){
if(typeof(Storage) !== "undefined"){
document.getElementById("name").innerHTML = localStorage.name;
document.getElementById("email").innerHTML = localStorage.email;
document.getElementById("adr").innerHTML = localStorage.adr;
document.getElementById("zip").innerHTML = localStorage.zip;
document.getElementById("cvv").innerHTML = localStorage.cvv;
}
}
</script>
why we are checking this condition, some browser does not support Web Storage
if(typeof(Storage) !== "undefined")
I found out my problem, my </form was placed wrongly. Sorry and thanks to everyone that helped!
I'm trying to disable submit button until first two fields have input. I've written a function to do that but for some reason it's not working.
Here is my HTML:
<html>
<Head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="Stuff.js"></script>
</Head>
<body>
<div class="container">
<form role="form">
<div class="form-group has-error">
<label for="FirstName">First Name</label>
<input type="text" class="form-control" id="First" placeholder="First Name">
</div>
<div class="form-group">
<label for="LastName">Last Name</label>
<input type="text" class="form-control" id="Last" placeholder="Last Name">
</div>
<div class="form-group">
<label for="Age">Age</label>
<input type="text" class="form-control" id="Age" placeholder="Age">
</div>
<button type="submit" class="btn btn-default" id="submit" >Submit</button>
</form>
</div>
</body>
This is my function:
$('#submit').keyup(function () {
if ($('#First').val() != "" && $('#Last').val() != "") {
$('#submit').removeattr('disabled');
} else {
$('#submit').attr('disabled', true);
}
});
You could use something like this:
$('#First, #Last').keyup(function () {
if ($('#First').val() !== "" && $('#Last').val() !== "") {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', true);
}
});
Note that you need to check the fields themselves upon keyup.
Also, use prop() to set the underlying boolean property of the disabled attribute to true/false, instead of removing it completely - see here for why.
jsFiddle here.