Validation of float and not empty in JavaScript - javascript

I am new to the world of web development and I am starting with basic applications. I am making a simple web page to add two numbers and trying to perform some basic validations that the input field can not be empty as well as the input must only be a float number.
My index.html:
<!doctype html>
<html lang="en">
<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.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="styles.css">
<link href="https://fonts.googleapis.com/css2?family=Merriweather&display=swap" rel="stylesheet">
<title>Add Two Numbers</title>
</head>
<body>
<form class="container center_div topSpacing">
<h1 id="Title" class="text-center">Add Two Numbers</h1>
<div class="form-group">
<label for="Num1">First Number</label>
<input type="text" class="form-control" id="Num1" placeholder="Enter First Number">
</div>
<div class="form-group">
<label for="Num2">Second Number</label>
<input type="text" class="form-control" id="Num2" placeholder="Enter Second Number">
</div>
<div class="text-center">
<button onclick="result()" type="button" class="btn btn-outline-success">Evaluate</button>
</div>
</form>
<br>
<h1 id="Title2" class="text-center"></h1>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
My index.js:
let var1 = document.getElementById("Num1");
let var2 = document.getElementById("Num2");
function validate() {
if(var1 == "" || var2 == "")
return false;
return true;
}
function buttonClick() {
let sum = parseFloat(var1.value) + parseFloat(var2.value);
return sum;
}
function result() {
if(validate()) {
document.getElementById("Title2").innerHTML = "Sum is: " + buttonClick();
} else {
window.alert("Wrong Inputs");
}
}
The JavaScript code is not performing the validation as well as the summation.

Simple fix for solution is make the input fields to type number.
<input type="number" class="form-control" id="Num1" placeholder="Enter First Number">
</div>
<input
type="number"
class="form-control"
id="Num2"
placeholder="Enter Second Number"
/>
change the validate function as below
function validate() {
const reg = /\-?\d+\.\d+/g;
if (
var1.value !== "" &&
var2.value !== "" &&
var1.value.match(reg) &&
var2.value.match(reg)
) {
return true;
}
return false;
}

Change this
function validate() {
if(var1 == "" || var2 == "")
return false;
return true;
}
to
function validate() {
if(var1.value == "" || var2.value == "")
return false;
else
return true;
}
this should work.

Related

How do we apply Bootstrap classes to JavaScript Error messages and make them stay on the screen when a form submit button is clicked?

I am trying to figure out how to make Javascript error messages be displayed in the DOM and stay there until valid information is added into the form inputs. Right now they appear for a brief moment and then disappear. On top of that, I have to use Bootstrap 5 to stylize the JavaScript Error messages. I've been trying to figure this out all day and I haven't had any luck.
I have my HTML and Javascript down below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login Form</title>
<link rel="stylesheet" href="login/login.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<main>
<h1 class="text-primary">Login</h1>
<form id="login_form" name="login_form" method="get">
<div>
<label for="email1">Email:</label>
<input name="email" type="email" autocomplete="email" id="email" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label for="password">Password:</label>
<input name="password" type="password" autocomplete="password" id="password" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label> </label>
<button type="submit" class="btn btn-primary" id="login">Login
</div>
</form>
</main>
</main>
<script defer src="login/login.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
const $ = selector => document.querySelector(selector);
document.addEventListener("DOMContentLoaded", () => {
$("#login").addEventListener("click", () => {
// get values user entered in textboxes
const email = $("#email");
const password = $("#password");
// create a Boolean variable to keep track of invalid entries
let isValid = true;
// check user entries - add text to error message if invalid
if (email.value == "" || password.value == "") {
email.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
password.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
return false;
} else {
email.nextElementSibling.textContent = "";
password.nextElementSibling.textContent = "";
}
if (email.value == "admin#example.com" && password.value == "password") {
document.writeln("Welcome back Admin!")
} else {
document.writeln("That email and password doesn't seem to be right. Try again.")
}
// submit the form if all entries are valid
if (isValid) {
$("#login_form").submit();
}
});
});

Uncaught TypeError: Cannot read properties of undefined (reading 'uname') and also No debugger available, can not send 'variables'

Here I'm trying to execute the following code but it throws the above error in console log in website page, I am unable to identify the error .
I have coded this webpage in such a way that it should show an error like "enter the user name" and "enter the password" whenever the input boxes are left empty but instead of this it is showing an uncaught type error. Kindly help me to find the solution.
my github code link is:https://github.com/harish-123445/login-form-using-html-css-javascript
function vfun(){
var uname=document.forms["myform"]["uname"].value;
var pword=document.forms["myform"]["pword"].value;
if(uname==null || uname=="" ){
document.getElementById("errorBox").innerHTML =
"enter the user name";
return false;
}
if(pword==null || pword==""){
document.getElementById("errorBox").innerHTML =
"enter the password";
return false;
}
if (uname != '' && pword != '' ){
alert("Login successfully");
}
}
<!DOCTYPE html>
<html >
<head>
<title>sign in form</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="js.js"></script>
<body>
<div class="box">
<img src="user.png" class="user">
<h1 >LOGIN HERE</h1>
<form class="myform" onsubmit= "return vfun()">
<p>USERNAME </p>
<input type="text" name="uname" placeholder="enter username" >
<p>PASSWORD </p>
<input type="password" name="pword" placeholder="enter password">
<div id="errorBox"></div>
<input type="submit" name="" value="login">
<br><br>
<a href="register.html" >Register for new user</a>
</form>
</div>
</body>
</head>
</html>
I have edited your code. I have called your username and password using getElementById and your two error boxes with different id names and now it is working fine.
function vfun(){
var uname=document.getElementById("name").value;
var psword=document.getElementById("passw").value;
if(uname==null || uname=="" ){
document.getElementById("errorBox2").innerHTML =
"enter the user name";
return false;
}
if(psword==null || psword==""){
document.getElementById("errorBox").innerHTML =
"enter the password";
return false;
}
if (uname != '' && pword != '' ){
alert("Login successfully");
}
}
<!DOCTYPE html>
<html >
<head>
<title>sign in form</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="js.js"></script>
<body>
<div class="box">
<img src="user.png" class="user">
<h1 >LOGIN HERE</h1>
<form class="myform" onsubmit= "return vfun()">
<p>USERNAME </p>
<input type="text" name="uname" id="name"
placeholder="enter username" >
<div id="errorBox2"></div>
<p>PASSWORD </p>
<input type="password" name="pword" id="passw"
placeholder="enter password">
<div id="errorBox"></div>
<input type="submit" name="" value="login">
<br><br>
<a href="register.html" >Register for new user</a>
</form>
</div>
</body>
</head>
</html>

Google Apps Script HTML form won't submit for overseas user

I have a small sidebar form that submits user data. It is all functional for anyone in the USA but if someone from overseas tries to submit the form, it fails. I even logged into the same user account as the one overseas and the form submits for me. I have never encountered an issue like this with GAS. The account the user is logged into owns the spreadsheet that the script is housed in and he has tried both local and US IP addresses to submit the data (not sure if this even matters.) What do I need to change/include in my scripts to allow all users to be able to submit the form? Would creating a Webapp and trigger be a fix?
Code.gs
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
//PROCESS FORM DATA
function processForm(formObject){
var notes = [formObject.client,
formObject.website,
formObject.email,
formObject.plan];
var mTabs = [formObject.client,
formObject.plan,
formObject.timeAllowed,
'',
'',
'00:00:00.000'];
pushToSheets(notes,mTabs);
}
//INCLUDE HTML PARTS, EG. JAVASCRIPT, CSS, OTHER HTML FILES
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
//THIS FUNCTION IS USED TO PUSH DATA TO EACH RESPECTIVE SHEET FROM THE SIDEBAR FORM SUBMISSION
function pushToSheets(notes,mTabs) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var noteTab = ss.getSheetByName('NOTES');
var sheetArr = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEPT','OCT','NOV','DEC'];
// var sheetArr = ['JAN','FEB'];
var nLast = noteTab.getLastRow();
noteTab.insertRowBefore(nLast+1);
noteTab.getRange(nLast+1, 1,1,4).setValues([notes]);
noteTab.getRange(2,1,nLast+1,17).sort([{column: 4, ascending: true}, {column: 1, ascending: true}])
for(var x = 0; x < sheetArr.length; x++) {
var sheet = ss.getSheetByName(sheetArr[x]);
var sLength = sheet.getLastRow();
sheet.insertRowBefore(sLength-1);
sheet.getRange(sLength-1, 1,1,6).setValues([mTabs]);
sheet.getRange(2, 1,sLength,11).sort([{column: 2, ascending: true}, {column: 1, ascending: true}])
}
}
Index.html
<!doctype html>
<html lang="en">
<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">
<?!= include('JavaScript'); ?> <!-- See JavaScript.html file -->
<title>Contact Details</title>
</head>
<body class="bg-secondary text-light">
<div class="container">
<?!= include('Form'); ?> <!-- See Form.html file -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<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.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$('#timeAllowed').keypress(function() {
var regex = new RegExp("^[0-9]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
if(this.value.length == 2){
this.value = this.value+':';
}
if(this.value.length == 5){
this.value = this.value+':00';
}
if(this.value.length > 7) {
return false;
}
});
</script>
</body>
</html>
Form.html
<form id="myForm" onsubmit="handleFormSubmit(this)" autocomplete="off">
<div class="form-group">
<label for="client">Client</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="clint" name="client" placeholder="Client Name">
</div>
<div class="form-group">
<label for="gender">Plan</label>
<select class="form-control form-control-sm" id="plan" name="plan" required>
<option value="" selected disabled>Choose...</option>
<option value="00 hosting">00 hosting</option>
<option value="01 slim">01 slim</option>
<option value="02 basic">02 basic</option>
<option value="10 special">10 special</option>
<option value="99 coming up">99 coming up</option>
</select>
</div>
<div class="form-group">
<label for="last_name">Time Allowed</label>
<input class="form-control form-control-sm" type="text" class="form-control" pattern="[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" title ="00:00:00" id="timeAllowed" name="timeAllowed" placeholder="00:00:00">
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control form-control-sm" type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="website">Website</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="website" name="website">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
JavaScript.html
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
Looks like I just needed to add this as a Webapp and that fixed the issue. Thank you for the suggestions!
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('test').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
function doGet() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
form.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return form;
}
test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<center>
<embed type="text/html" src="redacted" width="290" height="800">
</center>
</body>
</html>

javascript/html:make input fields required on checkbox check

So like I want to make an input field required when a checkbox is checked an 'not required' when it is unchecked...I've tried the following code but it was not working ...please help...
<form action="#">
<input id='req'><input type="submit"></form><input type="checkbox" onclick="req()" id="check">
<script>
function req(){
var req = document.getElementById("req");
var checkBox = document.getElementById("check");
if (checkBox.checked == true){
alert("checked")
req.required==true
} else {
alert("uncheck")
req.required==false
}
}
</script>
Give this a try:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
<form name="test" id="test" action="#" method="GET">
<div class="input-group">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="cbox">
<label class="form-check-label" for="cbox">Make field required</label>
</div>
</div><br>
<div class="input-group">
<input type="text" id="tbox" class="form-control">
</div><br>
<button type="submit" id="sub" class="btn btn-primary">Submit</button><br>
<small><span class="status"></span></small>
</form>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// On click of checkbox
$('#cbox').click(function() {
// Check if it's checked
if ($(this).prop('checked')) {
// Add the required attribute to the text input
$('#tbox').attr('required', '');
// log our results and display a small indicator span status
console.log('input is now required');
$('.status').text('input is now required');
} else {
// If it isn't checked, remove the required attribute
$('#tbox').removeAttr('required');
// log our results and display a small indicator span status
console.log('input is no longer required');
$('.status').text('input is no longer required');
}
});
});
</script>
</body>
</html>

Java script Validation on an html form in not working?

I coded an HTML form where I tried to validate it using javascript, However, the validation doesn't work. It should work on click of submit button. Everything looks fine! could not find the error! Please Help.
Below is the code for the page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Term Deposit Interest Calculator</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script>
function validateform(){
var amount=document.myform.amount.value;
var years=document.myform.years.value;
var interst= document.myform.interst.value;
if (amount==null || amount==""){
alert("Amount can't be blank");
return false;
}else if (years==null || years==""){
alert("Years can't be blank");
return false;
}else if (interest==null || interest==""){
alert("Interest can't be blank");
return false;
}
}
</script>
</head>
<body>
<div class="card">
<h3>Term Deposit Interest Calculator</h3><br>
<form name = "myform" method="post"onsubmit="return validateform()">
<input type="text" name="amount" placeholder="Deposit Amount"><span id="num1"></span>
<input type="text" name="years" placeholder="Number Of Years"><span id="num2"></span>
<input type="text" name="interest" placeholder="Yearly Interst Rate"><span id="num3"></span>
<input type="submit" name="submit" class="my submit" value="Total Amount">
</form>
<div class="result">
</div>
</div>
</body>
</html>
<?php
if (!isset($amount7032)) { $amount7032 = ''; }
if (!isset($interest7032)) { $interest7032 = ''; }
if (!isset($years7032)) { $years7032 = ''; }
?>
You have written wrong form element name at below line
var interst= document.myform.interst.value;
it should be
var interest= document.myform.interest.value;
Basically because javascript was not able to find the form element and it was failing due to that.
I tried below code and its working:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Term Deposit Interest Calculator</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script>
function validateform(){
var amount=document.myform.amount.value;
var years=document.myform.years.value;
var interest= document.myform.interest.value;
if (amount==null || amount==""){
alert("Amount can't be blank");
return false;
}else if (years==null || years==""){
alert("Years can't be blank");
return false;
}else if (interest==null || interest==""){
alert("Interest can't be blank");
return false;
}
}
</script>
</head>
<body>
<div class="card">
<h3>Term Deposit Interest Calculator</h3><br>
<form name="myform" method="post" onsubmit="return validateform()">
<input type="text" name="amount" placeholder="Deposit Amount"><span id="num1"></span>
<input type="text" name="years" placeholder="Number Of Years"><span id="num2"></span>
<input type="text" name="interest" placeholder="Yearly Interst Rate"><span id="num3"></span>
<input type="submit" name="submit" class="my submit" value="Total Amount">
</form>
<div class="result">
</div>
</div>
</body>
</html>

Categories