set focus in next html input after editing and clicking enter - javascript

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();
}
});

Related

Best way to remove the div area/spacing when using dismissible bootstrap alerts?

I've built a form on which I'm dynamically showing alerts(success and failure) based on if the data entered in the form is valid or invalid.
The problem I'm trying to fix is to remove the div/spacing at the initial instance when the form is loaded, or reloaded at a later point.
The spacing gets removed upon success and failure alerts , but once you reload the page, the spacing comes up . I want this empty space to be removed.
Can someone suggest me the easiest way to fix this using Bootstrap?
Here is my JS and HTML:
//fetching the element objects for which we want to perform manual validation
const userName = document.getElementById("name");
const userEmail = document.getElementById("email");
const pickupDate = document.getElementById("pickupDate");
const dropDate = document.getElementById("dropDate");
const phoneNumber = document.getElementById("phoneNumber");
let validName = false;
let validEmail = false;
let validpickupDate = false;
let validdropDate = false;
//validation for userName
userName.addEventListener("blur", () => {
let regName = /^[a-zA-Z]{2,30}$/; //starts with a-z orA-Z and no of characters b/w 2-30
if (regName.test(userName.value)) {
userName.classList.remove("is-invalid");
validName = true;
}
else {
userName.classList.add("is-invalid"); //adding "is-invalid" class to the userName field
validName = false;
}
})
//validation for userEmail
userEmail.addEventListener("blur", () => {
let regEmail = /^([_\-\.0-9a-zA-Z]+)#([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
if (regEmail.test(userEmail.value)) {
userEmail.classList.remove("is-invalid");
validEmail = true;
}
else {
userEmail.classList.add("is-invalid"); //adding "is-invalid" class to the userEmail field
validEmail = false;
}
})
//validation for pickupDate
pickupDate.addEventListener("blur", () => {
let todayDate = new Date(); //fetching today's date
let pickupDateObj = new Date(pickupDate.value); //converting the pickup date to date object since its a string
let dropDateObj = new Date(dropDate.value);
console.log(dropDate.value);
if (dropDate.value) {
if (pickupDateObj > todayDate) {
if (pickupDateObj > dropDateObj) {
alert("Enter a pickup date which is before drop date");
validpickupDate = false;
}
else {
pickupDate.classList.remove("is-invalid");
validpickupDate = true;
}
}
else {
pickupDate.classList.add("is-invalid");
validpickupDate = false;
}
}
else {
if (pickupDateObj > todayDate) {
pickupDate.classList.remove("is-invalid");
validpickupDate = true;
}
else {
pickupDate.classList.add("is-invalid");
validpickupDate = false;
}
}
})
//validation for pickupDate
dropDate.addEventListener("blur", () => {
let dropDateObj = new Date(dropDate.value);
console.log(dropDateObj);
if (pickupDate.value) {
console.log(pickupDate.value);
let pickupDateObj = new Date(pickupDate.value);
console.log(pickupDateObj);
if (dropDateObj > pickupDateObj) {
console.log(true)
dropDate.classList.remove("is-invalid");
validdropDate = true;
}
else {
console.log(false)
dropDate.classList.add("is-invalid");
validpickupDate = false;
}
}
else {
alert("Enter pickup date first");
validpickupDate = false;
}
})
let submit = document.getElementById("submit");
submit.addEventListener('click', (e) => {
e.preventDefault();
console.log("clicked");
if(validEmail && validName && validpickupDate && validdropDate){
let success = document.getElementById("success");
success.classList.add("show");
$('#failure').hide();
$('#success').show();
}
else{
let failure = document.getElementById("failure");
failure.classList.add("show");
$('#success').hide();
$('#failure').show();
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FormValidation</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div id="success" class="alert alert-success alert-dismissible fade" role="alert">
<strong>Success!</strong> Your form has been submitted successfully.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="failure" class="alert alert-danger alert-dismissible fade" role="alert">
<strong>Failure!</strong> Your form contains invalid data or data is missing
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="container my-2">
<h1>Car Rental Agency</h1>
<form>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter your name">
<div class="invalid-feedback">
Invalid user name
</div>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" id="email" placeholder="name#example.com">
<div class="invalid-feedback">
Invalid Email Id
</div>
</div>
<div class="form-group">
<label for="carSelect">Select Car</label>
<select class="form-control" id="carSelect">
<option>BMW i8</option>
<option>Audi A4</option>
<option>Porsche Cayenne</option>
<option>Rolls Royce Ghost</option>
</select>
</div>
<div class="form-group">
<label for="date">Select pickup date</label>
<input type="date" class="form-control" id="pickupDate">
<div class="invalid-feedback">
Pickup date must be after today's date
</div>
<div class="valid-feedback" style="color:red">
Pickup date must be before drop date
</div>
</div>
<div class="form-group">
<label for="date">Select drop date</label>
<input type="date" class="form-control" id="dropDate">
<div class="invalid-feedback">
Drop date must be after pickup date
</div>
</div>
<div class="form-group">
<label for="license">Enter driving license number</label>
<input type="text" class="form-control" id="license">
</div>
<div class="form-group">
<label for="phoneNumber">Enter your phone number</label>
<input type="text" class="form-control" id="phoneNumber">
</div>
<button class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
<script src="form.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.14.7/dist/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
I added a position absolute property so that I could move is wherever I wanted CodepenLink
Solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FormValidation</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div id="success" class="alert alert-success alert-dismissible fade" role="alert">
<strong>Success!</strong> Your form has been submitted successfully.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="failure" class="alert alert-danger alert-dismissible fade" role="alert">
<strong>Failure!</strong> Your form contains invalid data or data is missing
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="container my-2 mx-auto" style="position: absolute; top:0; left:25%; right:25%;">
<h1>Car Rental Agency</h1>
<form >
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter your name">
<div class="invalid-feedback">
Invalid user name
</div>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" id="email" placeholder="name#example.com">
<div class="invalid-feedback">
Invalid Email Id
</div>
</div>
<div class="form-group">
<label for="carSelect">Select Car</label>
<select class="form-control" id="carSelect">
<option>BMW i8</option>
<option>Audi A4</option>
<option>Porsche Cayenne</option>
<option>Rolls Royce Ghost</option>
</select>
</div>
<div class="form-group">
<label for="date">Select pickup date</label>
<input type="date" class="form-control" id="pickupDate">
<div class="invalid-feedback">
Pickup date must be after today's date
</div>
<div class="valid-feedback" style="color:red">
Pickup date must be before drop date
</div>
</div>
<div class="form-group">
<label for="date">Select drop date</label>
<input type="date" class="form-control" id="dropDate">
<div class="invalid-feedback">
Drop date must be after pickup date
</div>
</div>
<div class="form-group">
<label for="license">Enter driving license number</label>
<input type="text" class="form-control" id="license">
</div>
<div class="form-group">
<label for="phoneNumber">Enter your phone number</label>
<input type="text" class="form-control" id="phoneNumber">
</div>
<button class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
<script src="form.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.14.7/dist/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>

Using Javascript validation checks in a Django Project

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);

Reading international telephone in HTML [duplicate]

This question already has answers here:
Usage of the backtick character (`) in JavaScript
(11 answers)
Closed 1 year ago.
I am trying to get a user to input international phone number in HTML form, for it I am having to use JavaScript. I don't know JS, but after following a online blog I managed to cover some distance. But when I am trying to read the phone field it is displaying variable name instead of value. I think the problem is with this line of code in particular const phoneNumber = phoneInput.getNumber(); IDE saying it is a unresolved function.
Below is my file:
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--International phone input field-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
<!-- Bootstrap CSS -->
<link th:rel="stylesheet" th:href="#{/webjars/bootstrap/5.1.1/css/bootstrap.min.css} " />
<!-- font awesome-->
<link th:rel="stylesheet" th:href="#{/webjars/font-awesome/5.15.4/css/all.css} " />
<!-- local css file-->
<link href="/static/css/register_login.css" rel="stylesheet" th:href="#{/css/register_login.css}" />
<title>Easy Notifications App</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-10 col-xl-9 mx-auto">
<div class="card flex-row my-5 border-0 shadow rounded-3 overflow-hidden">
<div class="card-img-left d-none d-md-flex">
<!-- Background image for card set in CSS! -->
</div>
<div class="card-body p-4 p-sm-5">
<h5 class="card-title text-center mb-5 fw-light fs-5">Register</h5>
<form id="login" onsubmit="process(event)" action="#" th:action="#{/register}" th:object="${registerDto}" method="post">
<div class="form-floating mb-3">
<input type="text" th:field="*{firstName}" class="form-control" id="floatingInputfirstName" placeholder="First Name" autofocus>
<label for="floatingInputfirstName">First Name</label>
</div>
<div class="form-floating mb-3">
<input type="text" th:field="*{lastName}" class="form-control" id="floatingInputlastName" placeholder="Last Name">
<label for="floatingInputlastName">Last Name</label>
</div>
<div class="form-floating mb-3">
<input type="tel" class="form-control" id="tel" th:field="*{mobileNumber}" placeholder="Mobile Number">
<label for="tel"></label>
</div>
<div class="d-grid mb-2">
<button class="btn btn-lg btn-primary btn-login fw-bold text-uppercase" type="submit">
Register
</button>
</div>
</form>
<div class="alert alert-info" style="display: none;"></div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
<!-- Initialize the phone plugin -->
const phoneInputField = document.querySelector("#tel");
const phoneInput = window.intlTelInput(phoneInputField, {
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
});
const info = document.querySelector(".alert-info");
function process(event) {
event.preventDefault();
const phoneNumber = phoneInput.getNumber();
info.style.display = "";
info.innerHTML = 'Phone number in E.164 format: <strong>${phoneNumber}</strong>';
}
</script>
</html>
And here is the picture of error message:
Tried it and works with
info.innerHTML = `Phone number in E.164 format: <strong>${phoneNumber}</strong>`;
Usage of the backtick character (`) in JavaScript
There's something wrong the way you want to concat strings. If you really want to use the curly brackets, it should be like this, with the "`" quote:
info.innerHTML = `Phone number in E.164 format: <strong>${phoneNumber}</strong>`;
If you wanna use normal quote it can be done with the "+" operator:
info.innerHTML = "Phone number in E.164 format: <strong>" + phoneNumber + "</strong>";
Tested it and both should work.
Validate Phone Number by pattern in your input HTML element.
I think this is deprecated, but You can also use RegExp in Javascript.
See this Question
If you can get Phone Number value:
<form id="login" onsubmit="process(event)">
<div class="form-floating mb-3">
<input type="tel" class="form-control" id="tel" th:field="*{mobileNumber}" placeholder="Mobile Number">
<label for="tel"></label>
</div>
</form>
const process = (e) => {
e.preventDefault();
const phoneNumber = document.getElementById("tel").value;
info.style.display = "";
info.innerHTML = 'Phone number in E.164 format: <strong>${phoneNumber}</strong>';

How can I use javascript to enable a "create account" button once all fields have correct input?

What I am trying to accomplish and have been unable to figure out after reading from different sources all day is, how do I get the disabled attribute from a button to go away once all of the fields have input? At this point in time it doesn't really matter what is in the fields as long as they have something. I have worked on a addEventListener which I tried doing a if(validateForm()) createBtn.removeAttribute('disabled');
const form = document.getElementById('createForm')
// Selecting all text elements
const createBtn = document.getElementById('createBtn');
/*
methods to validate user input
*/
// validate that all fields have input
function validateForm() {
// get values from input
const studentIdValue = studentID.value.trim();
const emailValue = email.value.trim();
const usernameValue = username.value.trim();
const firstnameValue = firstname.value.trim();
const lastnameValue = lastname.value.trim();
const passwordValue = password.value.trim();
const password2Value = password_confirm.value.trim();
if(studentIdValue !== "" && emailValue !== "" && usernameValue !== "" && firstnameValue !== '' && lastnameValue !== '' && passwordValue !== '' && password2Value !== ''){
if(validateEmail(emailValue)) {
createBtn.disabled = false;
}
} else {
createBtn.disabled = true;
}
}
<html>
<head>
<script src="https://github.com/claudewill1/Project/blob/main/validate.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-between p-1">
<div class="col-12 col-md-6 nopadding">
<form action="" id="createform" method="post">
<div class="form-group">
<h2 class="form-title">Create a New Account</h2>
</div>
<!-- form-group -->
<!-- added ids to divs for input control to be able to access elements with script -->
<div class="form-group">
<div class="input-group">
<input class="form-control rounded-0" placeholder="Student ID" autofocus type="text" name="studentid" id="studentId" value="">
</div>
<!-- input-group -->
</div>
<!-- form-group -->
<div class="form-group">
<div class="input-group" id="email_div">
<input class="form-control rounded-0" placeholder="Email" autofocus type="text" name="email" value="">
</div>
<!-- input-group -->
</div>
<!-- form-group -->
<div class="form-group">
<div class="input-group" id="username_div">
<input class="form-control rounded-0" placeholder="Username" autofocus type="text" name="username" value="">
</div>
<!-- input-group -->
</div>
<!-- form-group -->
<div class="form-group">
<div class="input-group" id="firstname_div">
<input class="form-control rounded-0" placeholder="First name" autofocus type="text" name="firstname" value="">
</div>
<!-- input-group -->
</div>
<!-- form-group -->
<div class="form-group">
<div class="input-group" id="lastname_div">
<input class="form-control rounded-0" placeholder="Last name" autofocus type="text" name="lastname" value="">
</div>
<!-- input-group -->
</div>
<!-- form-group -->
<div class="form-group">
<div class="input-group">
<input class="form-control rounded-0" placeholder="Password" autofocus type="password" name="phash1" id="pass1_div" value="">
<div class="input-group-append">
<button class="btn btn-gold" type="button" id="show1" onclick="toggleInputType1()">
SHOW
</button>
</div>
</div>
<!-- input-group -->
</div>
<!-- form-group -->
<div class="form-group">
<div class="input-group">
<input class="form-control rounded-0" placeholder="Retype Password" autofocus type="password" name="phash2" id="pass2_div" value="">
<div class="input-group-append">
<button class="btn btn-gold" type="button" id="show2" onclick="toggleInputType2()">
SHOW
</button>
</div>
</div>
<!-- input-group -->
</div>
<!-- form-group -->
<div class="form-group pt-3">
<div class="input-group">
<!-- changed id for create button to "createBtn" -->
<button class="form-control rounded-0 btn-blue" type="button" id="createBtn" disabled onclick="btn_create()">
Create Account
</button>
</div>
<!-- input-group -->
<div class="input-group">
<button class="form-control rounded-0 btn-gold" type="button" id="submit" onclick="btn_home()">
Home
</button>
</div>
<!-- input-group -->
</div>
<!-- form-group -->
</form>
</div>
<!-- col-md -->
<div class="col nopadding">
<img class="side" src="./img/hero-image.jpg" alt="Hero Image">
</div>
<!-- col-6 -->
</div>
<!-- row -->
</div>
<!-- container -->
</body>
</html>
Can anyone point out what I might be doing wrong?
Also, please don't close my post as other have done in the past if I asked the question wrong, I am new for the most part to stackoverflow and I am posting based off the rules I see for posting. I made sure to only If needed I can edit this.
This works. I modified your validateForm() function a little and added another function that monitors the form for change.
function validateForm() {
"use strict";
//Check your HTML file. You'll need to add an id where there is none.
const studentIdValue = document.getElementById("studentid").value.trim();
const emailValue = document.getElementById("email").value.trim();
const usernameValue = document.getElementById("username").value.trim();
const firstnameValue = document.getElementById("firstname").value.trim();
const lastnameValue = document.getElementById("lastname").value.trim();
const passwordValue = document.getElementById("pass1_div").value.trim();
const password2Value = document.getElementById("pass2_div").value.trim();
if (studentIdValue !== "" && emailValue !== "" && usernameValue !== "" && firstnameValue !== "" && lastnameValue !== "" && passwordValue !== "" && password2Value !== "") {
document.getElementById("create-btn").removeAttribute("disabled");
}
}
//This function monitors the form for change.
function checkForm() {
"use strict";
const yourForm = document.getElementById("createform");
yourForm.addEventListener("change", function () {
validateForm();
});
}
checkForm();
You have to invoke validateForm() function on every input field update. You can do something like this with onkeyup event:
<input class="form-control rounded-0" placeholder="Student ID" autofocus type="text" name="studentid" id="studentId" value="" onkeyup="validateForm()">
That way once all the validation criteria are met your button should become active.
As an option you can definitely use event listeners outside of your html for each input field instead to trigger the validateForm().

Javascript doesn't work for input validation

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>";

Categories