how I validate JavaScript - javascript

Here when multiplying -1 to any variable it turns to negative. It uses for when the balance is withdrawn balance decreases but I set if the condition for validation for this reason -1 does not work. how I validate properly and balance also decreases when
<!doctype html>
<html lang="en">
<head>
<title>Bank || Project</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- css link -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="login-area" class="login-area">
<h1 class="bank-title">Welcome To Pioneer Bank</h1>
<div class="submit-area">
<h4>Login</h4>
<input type="text" class="form-control" placeholder="Email...">
<br>
<input type="password" class="form-control" placeholder="Password...">
<br>
<button type="submit" id="login-btn" class="btn btn-success">Submit</button>
</div>
</div>
<div id="transaction-area">
<div class="row">
<div class="col-md-4">
<div class=" deposit status">
<h5>Deposit</h5>
<h2>$ <span id="current-deposit">00</span></h2>
</div>
</div>
<div class="col-md-4 my-2 my-md-0">
<div class=" withdraw status">
<h5>Withdraw</h5>
<h2>$ <span id="current-withdraw">00</span></h2>
</div>
</div>
<div class="col-md-4">
<div class=" balance status">
<h5>Balance</h5>
<h2>$ <span id="current-balance">1240</span></h2>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="submit-area">
<h4>Deposit</h4>
<input type="text" id="deposit-amount" class="form-control" placeholder="$ amount you want to deposit">
<br>
<button id="deposit-btn" class="btn btn-success">Deposit</button>
</div>
</div>
<div class="col-md-6">
<div class="submit-area">
<h4>Withdraw</h4>
<input type="text" id="withdraw-amount" class="form-control" placeholder="$ amount you want to withdraw">
<br>
<button id="withdraw-btn" class="btn btn-success">Withdraw</button>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
Here when multiplying -1 to any variable it turns to negative. It uses for when the balance is
withdrawn balance decreases but I set if the condition for validation for this reason -1 does not
ork. how I validate properly and balance also decreases when
// LOGIN BUTTON EVENT HANDLER
const loginBtn = document.getElementById('login-btn');
loginBtn.addEventListener('click', function () {
const loginArea = document.getElementById('login-area');
loginArea.style.display = 'none';
const transactionArea = document.getElementById('transaction-area');
transactionArea.style.display = 'block';
})
//deposit handler
const depositBtn = document.getElementById('deposit-btn');
depositBtn.addEventListener('click', function() {
const depositNumber = getInputNumber("deposit-amount");
updateSpanText("current-deposit", depositNumber)
updateSpanText("current-balance", depositNumber);
})
// withdraw button handler
const withdrawBtn = document.getElementById("withdraw-btn");
withdrawBtn.addEventListener("click", function() {
const withdrawNumber = getInputNumber("withdraw-amount");
updateSpanText("current-withdraw", withdrawNumber);
updateSpanText("current-balance", withdrawNumber;
})
function getInputNumber(id) {
const amount = document.getElementById(id).value;
const amountNumber = parseFloat(amount);
document.getElementById(id).value = "";
return amountNumber;
}
Here when multiplying -1 to any variable it turns to negative. It uses for when the balance
is withdrawn balance decreases but I set if the condition for validation for this reason -1 does
not work. how I validate properly and balance also decreases when
function updateSpanText(id, depositNumber) {
if (depositNumber >= 0 && depositNumber !== '') { //here I set if condtition
var currentBalance = document.getElementById(id).innerText;
const currentBalanceNumber = parseFloat(currentBalance);
const totalBalance = depositNumber + currentBalanceNumber;
document.getElementById(id).innerText = totalBalance;
} else {
console.log(alert('Invalid input value'));
}
</script>
withdraw.

Here is what you want:
// LOGIN BUTTON EVENT HANDLER
const loginBtn = document.getElementById('login-btn');
loginBtn.addEventListener('click', function () {
const loginArea = document.getElementById('login-area');
loginArea.style.display = 'none';
const transactionArea = document.getElementById('transaction-area');
transactionArea.style.display = 'block';
})
//deposit handler
const depositBtn = document.getElementById('deposit-btn');
depositBtn.addEventListener('click', function () {
const depositNumber = getInputNumber("deposit-amount");
updateSpanText("current-deposit", depositNumber)
updateSpanText("current-balance", depositNumber);
})
// withdraw button handler
const withdrawBtn = document.getElementById("withdraw-btn");
withdrawBtn.addEventListener("click", function () {
const withdrawNumber = getInputNumber("withdraw-amount");
updateSpanText("current-withdraw", withdrawNumber);
updateSpanText("current-balance", withdrawNumber, true);
})
function getInputNumber(id) {
const amount = document.getElementById(id).value;
const amountNumber = parseFloat(amount);
document.getElementById(id).value = "";
return amountNumber;
}
function updateSpanText(id, depositNumber, isWithdraw = false) {
if (depositNumber >= 0 && depositNumber !== '') { //here I set if condtition
var currentBalance = document.getElementById(id).innerText;
const currentBalanceNumber = parseFloat(currentBalance);
const totalBalance = currentBalanceNumber + (isWithdraw ? -depositNumber : depositNumber);
document.getElementById(id).innerText = totalBalance;
} else {
console.log(alert('Invalid input value'));
}
}
<!doctype html>
<html lang="en">
<head>
<title>Bank || Project</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- css link -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="login-area" class="login-area">
<h1 class="bank-title">Welcome To Pioneer Bank</h1>
<div class="submit-area">
<h4>Login</h4>
<input type="text" class="form-control" placeholder="Email...">
<br>
<input type="password" class="form-control" placeholder="Password...">
<br>
<button type="submit" id="login-btn" class="btn btn-success">Submit</button>
</div>
</div>
<div id="transaction-area">
<div class="row">
<div class="col-md-4">
<div class=" deposit status">
<h5>Deposit</h5>
<h2>$ <span id="current-deposit">00</span></h2>
</div>
</div>
<div class="col-md-4 my-2 my-md-0">
<div class=" withdraw status">
<h5>Withdraw</h5>
<h2>$ <span id="current-withdraw">00</span></h2>
</div>
</div>
<div class="col-md-4">
<div class=" balance status">
<h5>Balance</h5>
<h2>$ <span id="current-balance">1240</span></h2>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="submit-area">
<h4>Deposit</h4>
<input type="text" id="deposit-amount" class="form-control"
placeholder="$ amount you want to deposit">
<br>
<button id="deposit-btn" class="btn btn-success">Deposit</button>
</div>
</div>
<div class="col-md-6">
<div class="submit-area">
<h4>Withdraw</h4>
<input type="text" id="withdraw-amount" class="form-control"
placeholder="$ amount you want to withdraw">
<br>
<button id="withdraw-btn" class="btn btn-success">Withdraw</button>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

Related

Displaying user input in the table form using Javascript DOM

i have trouble displaying users' input and have spent some time looking at it and unsure which part had gone wrong. I am supposed to display the "Result" word in green and display user's input in a form of table. I used document.getElementsByClassName('container').innerHTML to add new element in the homepage.
Could anyone explain why the word Result and table doesn't show?
My code:
/*** Home ***/
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="mhsavings.js"></script>
</head>
<style>
.main-content{
width:70%;
/* background-color: lightblue; */
text-align: center;
}
</style>
<body>
<div class="container main-content">
<h1 style="margin-top:40px; margin-bottom: 30px;">Savings</h1>
<h3 style="color:blue;margin-bottom:48px;">How long does it takes for me to reach My Goal?</h3>
<form>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon1">Initial Amount ($)</span>
<input type="text" class="form-control" placeholder="" aria-label="initial Amt" aria-describedby="basic-addon1" id="initialAmt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon2">Yearly interest (%)</span>
<input type="text" class="form-control" aria-label="yearly interest" aria-describedby="basic-addon2" id="yearlyInt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon3">My Goal</span>
<input type="text" class="form-control" id="goal" aria-describedby="basic-addon3" id="goal">
</div>
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
</form>
</div>
</body>
</html>
/*** in JS file ***/
function calculate(){
'use stict';
var initialAmt = document.getElementById("initialAmt");
var yearlyInt = document.getElementById("yearlyInt");
var goal = document.getElementById("goal");
console.log(goal.value);
var receive = Math.round(initialAmt, 2);
var years = 0;
while (receive < goal) {
receive *= (1 + yearlyInt);
years += 1;
}
// console.log(document.getElementsByClassName('container'));
document.getElementsByClassName('container').innerHTML = "<h3 style='color:green; margin-bottom: 20px'>Result</h3>";
document.getElementsByClassName('container').innerHTML = `<table style='width: 500px'>
<tr>
<th>You will achieve your goal in (years):</th>
<td>${years}</td>
</tr>
<tr>
<th>You will get ($):</th>
<td>${receive}</td>
</tr>
</table>`;
}
#1: name of function not the function execution!
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
to
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate">Calculate</button>
#2: getElementsByClassName returns a collection not an element!
#3: lacking of parseInt before calculating
Beside the comments from other user posted in your original question,you code has many incorrect points:
You need to use value to get the input value,so change var initialAmt = document.getElementById("initialAmt"); to var initialAmt = document.getElementById("initialAmt").value;
When use innerHTML,you need to append the value,make sure not to override it
function calculate(){
'use stict';
var initialAmt = parseInt(document.getElementById("initialAmt").value);
var yearlyInt = parseInt(document.getElementById("yearlyInt").value);
var goal = parseInt(document.getElementById("goal").value);
var receive = Math.round(initialAmt, 2);
var years = 0;
while (receive < goal) {
receive *= (1 + yearlyInt);
years += 1;
}
// console.log(document.getElementsByClassName('container'));
var result = document.createElement("div");
var content = "<h3 style='color:green; margin-bottom: 20px'>Result</h3>";
content += `<table style='width: 500px;border:1px'>
<tr>
<th>You will achieve your goal in (years):</th>
<td>`+years+`</td>
</tr>
<tr>
<th>You will get ($):</th>
<td>`+receive+`</td>
</tr>
</table>`;
result.innerHTML = content;
document.getElementsByClassName('container')[0].appendChild(result);
}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="mhsavings.js"></script>
</head>
<style>
.main-content{
width:70%;
/* background-color: lightblue; */
text-align: center;
}
</style>
<body>
<div class="container main-content">
<h1 style="margin-top:40px; margin-bottom: 30px;">Savings</h1>
<h3 style="color:blue;margin-bottom:48px;">How long does it takes for me to reach My Goal?</h3>
<form>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon1">Initial Amount ($)</span>
<input type="text" class="form-control" placeholder="" aria-label="initial Amt" aria-describedby="basic-addon1" id="initialAmt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon2">Yearly interest (%)</span>
<input type="text" class="form-control" aria-label="yearly interest" aria-describedby="basic-addon2" id="yearlyInt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon3">My Goal</span>
<input type="text" class="form-control" id="goal" aria-describedby="basic-addon3" id="goal">
</div>
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
</form>
</div>
</body>
</html>
Using your functio, you may use this code
form fields are text fields. With parseInt() a text string is converted into an integer.
Below I added an extra <div id="result"></div> but if you want to use the container div, you can target this div with document.querySelector(".container").innerHTML = .... This will select the first class with that name. Note that this will replace all html code in the form!
function calculate(){
'use stict';
let initialAmt = parseInt( document.getElementById("initialAmt").value );
let yearlyInt = parseInt( document.getElementById("yearlyInt").value );
let goal = parseInt( document.getElementById("goal").value );
let receive = Math.round(initialAmt, 2);
let years = 0;
while (receive < goal) {
receive *= (1 + yearlyInt);
years += 1;
}
let result = '<h3 style="color:green; margin-bottom: 20px">Result</h3><table style="width: 500px"><tr><th>You will achieve your goal in (years):</th><td>' + years + '</td></tr><tr><th>You will get ($):</th><td>' + receive + '</td></tr></table>';
document.getElementById("result").innerHTML = result;
}
.main-content{
width:70%;
/* background-color: lightblue; */
text-align: center;
}
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div class="container main-content">
<h1 style="margin-top:40px; margin-bottom: 30px;">Savings</h1>
<h3 style="color:blue;margin-bottom:48px;">How long does it takes for me to reach My Goal?</h3>
<form>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon1">Initial Amount ($)</span>
<input type="text" class="form-control" placeholder="" aria-label="initial Amt" aria-describedby="basic-addon1" id="initialAmt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon2">Yearly interest (%)</span>
<input type="text" class="form-control" aria-label="yearly interest" aria-describedby="basic-addon2" id="yearlyInt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon3">My Goal</span>
<input type="text" class="form-control" id="goal" aria-describedby="basic-addon3" id="goal">
</div>
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
</form>
<div id="result"></div>
</div>

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>

set focus in next html input after editing and clicking enter

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

How can I add line break in userform?

I'm using "script app" from google sheets and I need to allow line break in the "userform" that I have created, I will use this to feed data to my google sheet and some of the items need multiple lines in the same cell.
Is there anyway I can do that?
EXAMPLE
EXAMPLE 2
CODE
function showAdicionarClienteHTML() {
var template = HtmlService.createTemplateFromFile("AdicionarClienteHTML");
var html = template.evaluate();
html.setTitle("ADICIONAR CLIENTE").setHeight(800).setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html, "Adicionar novo cliente:");
//.showModalDialog(html, "Adicionar novo cliente:");
//.showSidebar(html);
}
function appendData(data){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Clientes");
ws.appendRow([data.name,data.login,data.sninv,data.numero,data.sndtl,data.tele,data.regiao]);
}
HTML
<!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="nome" type="text" class="validate">
<label for="nome">Nome</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">mail_outline</i>
<input id="login" type="text" class="validate">
<label for="login">E-Mail ou Login</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">select_all</i>
<input id="sninv" type="text" class="validate">
<label for="sninv">S/N do Inversor</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">format_list_numberedl</i>
<input id="numero" type="text" class="validate">
<label for="numero">Numero do Inversor</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">select_all</i>
<input id="sndtl" type="text" class="validate">
<label for="sndtl">S/N do Datalogger</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">phone_in_talk</i>
<input id="tele" type="tel" class="validate">
<label for="tele">Telefone</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">explore</i>
<input id="regiao" type="text" class="validate">
<label for="regiao">Região</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action" id="btn">Adicionar
<i class="material-icons right">send</i>
</button>
</div><!--END ROW -->
</div><!--END CONTAINER -->
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
var nameBox = document.getElementById("nome");
var loginBox = document.getElementById("login");
var sninvBox = document.getElementById("sninv");
var numeroBox = document.getElementById("numero");
var sndtlBox = document.getElementById("sndtl");
var teleBox = document.getElementById("tele");
var regiaoBox = document.getElementById("regiao");
document.getElementById("btn").addEventListener("click",addRecord);
function addRecord(){
var name = nameBox.value;
var login = loginBox.value;
var sninv = sninvBox.value;
var numero = numeroBox.value;
var sndtl = sndtlBox.value;
var tele = teleBox.value;
var regiao = regiaoBox.value;
if(name.trim().length == 0 || login.trim().length == 0 || sninv.trim().length == 0 || numero.trim().length == 0 || sndtl.trim().length == 0 || tele.trim().length == 0 || regiao.trim().length == 0){
//handle error
M.toast({html: 'Preencha todos os campos!'})
} else {
var data ={
name: nameBox.value,
login: loginBox.value,
sninv: sninvBox.value,
numero: numeroBox.value,
sndtl: sndtlBox.value,
tele: teleBox.value,
regiao: regiaoBox.value
};
google.script.run.appendData(data);
}//CLOSE ELSE
}//CLOSE ADD RECORD
</script>
</body>
</html>
The <input> tag doesn't support line breaks. If you want to add a multi-line input, you have to use <textarea> instead. So you should change all the elements which could potentially have several lines from <input> to <textarea>.
That is, you should change these lines:
<input id="sninv" type="text" class="validate">
<input id="numero" type="text" class="validate">
<input id="sndtl" type="text" class="validate">
To these ones:
<textarea id="sninv" type="text" class="validate"></textarea>
<textarea id="numero" type="text" class="validate"></textarea>
<textarea id="sndtl" type="text" class="validate"></textarea>
This way, you can add multi-line text, which will still be a multi-line when you send it to the spreadsheet.
Reference:
<textarea>
I hope this is of any help.

Input type=file validation stops other input types validation

I'm trying to use jquery form validator to validate a form that has multiple input fields and a mandatory file upload. For brevity, I reduced 1 text input field and 1 file upload field on my sample. The problem is every time a file is selected for upload then the validation on other field will not function.
< script >
$.validate({
form: '#frmSlide',
modules: 'file',
validateOnBlur: false,
errorMessagePosition: 'top', // Instead of 'element' which is default
scrollToTopOnError: false, // Set this property to true if you have a long form
onError: function($form) {
alert('Failed!');
},
onSuccess: function($form) {
alert('ok!');
return false; // Will stop the submission of the form
},
onElementValidate: function(valid, $el, $form, errorMess) {
console.log('Input ' + $el.attr('name') + ' is ' + (valid ? 'VALID' : 'NOT VALID'));
}
});
$("#imgfile").on('change', function() {
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image img-thumbnail"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
}); < /script>
<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">
<meta name="description" content="">
<title></title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Aguafina+Script">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="css/theme.min.css">
<link rel="stylesheet" href="css/styles.css">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link rel="stylesheet" href="css/ie10-viewport-bug-workaround.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/3.1.1/css/font-awesome.css" />
<link rel="stylesheet" href="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.8/theme-default.min.css" />
<link rel="stylesheet" href="css/typeaheadjs.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.11/css/dataTables.bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.8/jquery.form-validator.min.js"></script>
</head>
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSlide">
<div class="form-group">
<label class="col-sm-4 control-label" for="imgfile">Image file</label>
<div class="col-sm-8">
<input type="file" id="imgfile" data-validation="required ratio mime size" data-validation-allowing="jpg, png, gif" />
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-md-offset-4" id="image-holder">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="seq">Sequence</label>
<div class="col-sm-8">
<input class="form-control server" name="f_seq" id="f_seq" data-validation="number" data-validation-allowing="range[1;4]" type="text" value="" placeholder="Enter 1-4" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button name="btnUpd" id="btnUpd" type="submit" class="clsUpd btn btn-primary"><i class="fa fa-floppy-o"></i> Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</html>
Can anyone shed me light on how to fix it? Thanks.
Just change the ratio validation to data-validation-ratio="1:1" (or any ratio you want) instead of "ratio" in the data-validation. Working fiddle here - https://jsfiddle.net/Sanjeevi/s9o7273r/
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSlide">
<div class="form-group">
<label class="col-sm-4 control-label" for="seq">Sequence</label>
<div class="col-sm-8">
<input class="form-control server" name="f_seq" id="f_seq" data-validation="number" data-validation-allowing="range[1;4]" type="text" value="" placeholder="Enter 1-4" />
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="imgfile">Image file</label>
<div class="col-sm-8">
<input type="file" id="imgfile" data-validation="required mime size" data-validation-allowing="jpg, png, gif" data-validation-ratio="1:1"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-md-offset-4" id="image-holder">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button name="btnUpd" id="btnUpd" type="submit" class="clsUpd btn btn-primary"><i class="fa fa-floppy-o"></i> Update</button>
</div>
</div>
</form>
</div>
</div>
</div>

Categories