How to display results from a JavaScript function to an html element - javascript

I am having trouble figuring out how to display values from a JavaScript to a table in HTML. I am trying to display just the even numbers between a starting number and a ending number. I believe my functions are correct but for some reason the values do not display on the page when submitted. Any help would be awesome. Thanks
function clearErrors() {
for (var loopCounter = 0; loopCounter < document.forms["displayEvens"].elements.length; loopCounter++) {
if (document.forms["displayEvens"].elements[loopCounter]
.parentElement.className.indexOf("has-") != -1) {
document.forms["displayEvens"].elements[loopCounter]
.parentElement.className = "form-group";
}
}
}
function resetForm() {
clearErrors();
document.forms["displayEvens"]["startingNumber"].value = "";
document.forms["displayEvens"]["endingNumber"].value = "";
document.forms["displayEvens"]["step"].value = "";
document.getElementById("results").style.display = "none";
document.getElementById("submitButton").innerText = "DisplayEvens";
document.forms["displayEvens"]["startingNumber"].focus();
}
function displayEvens(startingNumber, endingNumber, step) {
var startingNumber =
parseInt(document.getElementById("startingNum").value);
var endingNumber = parseInt(document.getElementById("endingNum").value);
var step = parseInt(document.getElementById("stepNum").value);
var evenNums = [];
for (var i = startingNumber; i < endingNumber; i += step) {
if (i % 2 == 0) {
evenNums.push(i);
}
}
document.getElementById("evens").innerText = evenNums;
}
function validateItems() {
clearErrors();
displayEvens(startingNumber, endingNumber, step);
console.trace("got here!");
//var startingNumber = document.forms["displayEvens"]
["startingNumber"].value;
//var endingNumber = document.forms["displayEvens"]
["endingNumber"].value;
//var step = document.forms["displayEvens"]["step"].value;
if (startingNumber == "" || isNaN(startingNumber)) {
alert("Starting Number must be filled in with a number.");
document.forms["displayEvens"]["startingNumber"]
.parentElement.className = "form-group has-error";
document.forms["displayEvens"]["startingNumber"].focus();
return false;
}
if (endingNumber == "" || isNaN(endingNumber)) {
alert("Ending Number must be filled in with a number.");
document.forms["displayEvens"]["endingNumber"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["endingNumber"].focus();
return false;
}
if (endingNumber <= startingNumber) {
alert("Ending Number must be greater than the Starting number.");
document.forms["displayEvens"]["endingNumber"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["endingNumber"].focus();
return false;
}
if (step == "" || isNaN(step)) {
alert("Step Number must be filled in with a number.");
document.forms["displayEvens"]["step"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["step"].focus();
return false;
}
if (step < 0) {
alert("Step Number must be filled in with a positive number.");
document.forms["displayEvens"]["step"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["step"].focus();
return false;
}
//document.getElementById("results").style.display = "block";
//document.getElementById("submitButton").innerText = "Recalculate";
document.getElementById("startingNum").innerText =
Number(startingNumber);
document.getElementById("endingNum").innerText = Number(endingNumber);
document.getElementById("stepNum").innerText = Number(step);
document.getElementById("evens").innerText = Number(evenNums);
return false;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript" src="displayEvens.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>Display Evens</h1>
<form name="displayEvens" onsubmit="return validateItems();" onreset="resetForm();">
<div class="form-group row">
<label for="startingNumber" class="col-sm-2 col-form-
label">Starting Number</label>
<div class="col-sm-10">
<input type="number" class="form-control" ` id="startingNumber" ` placeholder="Enter a number" />
</div>
</div>
<div class="form-group row">
<label for="endingNumber" class="col-sm-2 col-form-`
label">Ending`
Number</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="endingNumber" placeholder="Enter a number" />
</div>
</div>
<div class="form-group row">
<label for="step" class="col-sm-2 col-form-
label">Step</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="step" placeholder="Enter a number" />
</div>
</div>
<button type="submit" id="submitButton" class="btn btn-
default">Display Evens</button>
<button type="reset" id="resetButton" class="btn">Reset</button>
</form>
</br>
<table id="results" class="table table-striped">
<thead>
<tr>
<td>Even numbers between <span id="startingNum"></span> and
<span id="endingNum"></span> by <span id="stepNum"></span></td>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td><span id="evens"></span></td>
</tbody>
</table>
</div>
<!--<div id="results" style="display:none;">
<h3>Results:</h3>
<span id="evens"></span>
<h3>Your Starting Number:</h3>
<span id="start"></span></br>
<h3>Your Ending Number:</h3>
<span id="end"></span></br>
<h3>Your Step Number:</h3>
<span id="step"></span>
</div>-->
</body>
</html>

There's a fundamental issue wrong with your html. You are using the same id attribute on multiple elements. The id attribute should be used only on one element because it is a unique identifier.
Also when you have cleaned that up you can change your line
document.getElementById("endingNum").innerText = Number(endingNumber);
replace it with
document.getElementById("endingNum").append(Number(endingNumber))
instead

Related

JavaScript can not get alert box

So basically, I'm trying to do client side validation through JavaScript, but the code does not seem to be working. I am not getting any alert box. Below is HTML Form and JavaScript. I have skipped html and Body tags for obvious reasons. Can someone look over and see where am I making a mistake?
HTML form
<div class="container" >
<h1 style="text-align: center;">Online Vaccine Registration Form</h1>
<h1 style="text-align: center;">Developed by yourname</h1>
<form method="post" name="vacform" onsubmit=" return validateForm()">
<table>
<div class="row">
<div class="form-group col-md-6">
<label for="Name">Name : </label>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
<div class="form-group col-md-6">
<label for="CNIC" >CNIC : </label>
<input type="text" class="form-control" name="CNIC" placeholder="CNIC">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="Mob">Mobile : </label>
<input type="number" class="form-control" name="Mob" placeholder="Mobile">
</div>
<div class="form-group col-md-6">
<label for="Dob" >DoB : </label>
<input type="date" class="form-control" name="DoB">
</div>
</div>
<div class="form-group">
<label for="cen">Nearby centre</label>
<select class="form-control" id="sel1">
<option selected disabled>Select your Nearest Centre</option>
<option>Karachi West</option>
<option>Karachi East</option>
<option>Karachi North</option>
<option>Karachi Central</option>
<option>Malir</option>
</select>
</div>
</table>
<button type="button" class="btn btn-primary">Submit</button>
</form>
</div>
JavaScript
function validateForm()
{
var varname = document.vacform.name.value;
var varcnic = document.vacform.CNIC.value;
var varMob = document.vacform.Mob.value;
var varDoB = new Date(DoB);
var limitdate = new Date('2010-01-01');
var CNlength = 13;
var num = /^[0-9]+$/;
var str = /^[A-Za-z]+$/;
if(document.vacform.name.value!="")
{
if(document.vacform.CNIC.value!="")
{
if(document.vacform.Mob.value!="")
{
if(document.vacform.DoB.value!="")
{
if(varname.match(str))
{
if(varcnic.lenght == CNlength)
{
if(varcnic.match(num))
{
if(varDoB.getYear() < limitdate.getYear())
{
alert("All types of Validations have been done")
return true;
}
else
{
alert("Date should be less than 01-01-2010")
return false;
}
}
else
{
alert("CNIC field should have numbers only")
return false;
}
}
else
{
alert("CNIC lenght should be 13")
return false;
}
}
else
{
alert("Name can only contain letters")
return false;
}
}
else
{
alert("Date of Birth must be entered")
return false;
}
}
else
{
alert("Please Enter your mobile number")
return false;
}
}
else
{
alert("CNIC number Required")
return false;
}
}
else
{
alert("Name field can not be empty")
return false;
}
}
</script>
You call the function from the onsubmit event handler, however you never submit the form so it can't be triggered.
<button type="button" class="btn btn-primary">Submit</button>
This kind of button is for hooking JS into. It isn't a submit button.
Set type="submit" or remove the type attribute entirely (submit is the default).
Also address the errors in your HTML that a validator would highlight.

Disable a button if (length < x)

good evening.
I'm a beginner with JavaScript and I'm trying to recreate a specific webpage. There, exists a button that, if the login form doesn't have at least 11 elements on user and 8 on password, the button is disabled.
How can I do this with HTML and JS?
function blockButtonByUser() {
var cpfleng = document.getElementById('.iptuser').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
function blockButtonByPassword() {
var passwordlength = document.getElementById('.iptpassword').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit'>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
Thanks for the help!
Here is something like that using an eventListener:
var cpfOkay = false
var passwordOkay = false;
var btnsubmit = document.getElementsByClassName('btnsubmit')[0];
document.getElementById('cpf').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
cpfOkay = false;
if (event.target.value.length >= 11) {
cpfOkay = true;
}
checkBoth();
})
document.getElementById('password').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
passwordOkay = false;
if (event.target.value.length >= 8) {
passwordOkay = true;
}
checkBoth();
})
function checkBoth() {
btnsubmit.disabled = true;
btnsubmit.style.opacity = 0.5;
if (cpfOkay && passwordOkay) {
btnsubmit.disabled = false;
btnsubmit.style.opacity = 1;
}
}
<header><img src="https://placekitten.com/200/300" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' disabled style="opacity:0.5">
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
You can add event listeners for input event for both the user and password, and based on requirements you can enable or disable the button. You can refactor your code like this:
var cpf = document.getElementById('cpf')
var password = document.getElementById('password')
var btnsubmit = document.getElementById('btnsubmit')
cpf.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
password.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' id='btnsubmit' disabled>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
<script src="main.js"></script>
You have a few issues. One was getElementById on classes. One was no event handler. Lastly, you were trying to get the length on the element, but not the length of the value.
This should work:
document.querySelector('.btnsubmit').addEventListener('click', e =>{
blockButtonByUser();
blockButtonByPassword()
})
function blockButtonByUser(){
var cpfleng = document.querySelector('.iptuser').value.length
console.log(cpfleng)
var btnsubmit = document.querySelector('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}
function blockButtonByPassword(){
var passwordlength = document.querySelector('.iptpassword').value.length
console.log(passwordlength)
var btnsubmit = document.querySelector('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}

How to delay form submission

I'm working on a basic webform for my beginning Javascript class. I pretty much have all my expected results (assignment covers input validation and storing elements in an array by name), except for the fact that when I submit the form, I'd like to give a 5 second delay from the time I hit submit to when the page redirects. This delay is so that user will be able to cancel the order.
From what we have learned in class so far, I would expect I perform this action with a setTimeout block of code- though I haven't been able to work that yet. My form submission is dependent on a true/false return value from the called function, and I'd like to delay that true value from hitting so quickly. I've attached my full HTML file but the block of code that I'm wondering why it isn't working in particular is this:
setTimeout(function() {
return true;
}, 5000);
The first problem I observe when debugging in Chrome is that this doesn't return the True value back to the surrounding code.
I think that something could be done with jQuery to circumvent this but we haven't covered any of that so I'd like to avoid going that route.
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="Costello Improved">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Costellos Pasta and Pizza</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="costello.css">
</head>
<body>
<form name="myForm" action="https://costello-pasta.glitch.me/order" id="myForm" method="POST" onsubmit="return calculateOrder(this)">
<div class="container">
<div class="row">
<div class="col-md-12" id="debug">Costello's Online Orders</div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta Bowl</div>
<div class="col-md-4"> (basic price: $7.50)</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta</div>
<div class="col-md-4">
<div><input type="radio" name="pastatype" value="0" />Spaghetti (no extra cost)</div>
<div><input type="radio" name="pastatype" value="50" />Fettucine (add 50 cents)</div>
<div><input type="radio" name="pastatype" value="75" />Fusilli (add 75 cents)</div>
</div>
<div class="col-md-4 msg" id="radioLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Sauce</div>
<div class="col-md-4">
<select name="sauce">
<option value="0">Pomodoro (no extra cost)</option>
<option value="50">Bolognese (add 50 cents)</option>
<option value="100">Alfredo (add $1.00)</option>
</select>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Extras</div>
<div class="col-md-4">
<div><input type="checkbox" name="extras" value="200" />Side salad (add $2.00)</div>
<div><input type="checkbox" name="extras" value="100" />Bread sticks (add $1.00)</div>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Name</div>
<div class="col-md-4"><input type="text" id="name" name="client_name" /></div>
<div class="col-md-4 msg" id="nameLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Phone</div>
<div class="col-md-4"><input type="text" id="phone" value="" /></div>
<div class="col-md-4 msg" id="phoneLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label"><input type="submit" value="Order" /></div>
<div class="col-md-4" id="totalcost"></div>
<div class="col-md-4 msg" id="submitMessage"></div>
</div>
</div>
</form>
</body>
<script>
function calculateOrder() {
var totalCost = 750;
//Storing Pasta radio buttons into array. Iterating through array and adding checked selection's value to the total cost.
var submitBool = true;
var pastaArray = document.getElementsByName('pastatype');
for (var i = 0; i < pastaArray.length; i++) {
if (pastaArray[i].checked == true) {
totalCost = totalCost + parseInt(pastaArray[i].value);
}
//Validating Pasta input
}
if (pastaArray[0].checked == false && pastaArray[1].checked == false && pastaArray[2].checked == false) {
document.getElementById('radioLabel').innerHTML = "Required field! (You must choose a pasta)";
submitBool = false;
} else {
document.getElementById('radioLabel').innerHTML = "";
}
//Storing sauce selection into an array. Adding price for selected option.
var sauceArray = document.getElementsByName('sauce');
totalCost = totalCost + parseInt(sauceArray[0].value);
//Storing extras selection(s) into an array. Adding prices for selected options.
var extraArray = document.getElementsByName('extras');
for (var x = 0; x < extraArray.length; x++) {
if (extraArray[x].checked == true) {
totalCost = totalCost + parseInt(extraArray[x].value);
}
}
//Validating Name input
if (document.getElementById('name').value == "") {
document.getElementById('nameLabel').innerHTML = "Required field! Enter your name.";
submitBool = false;
} else {
document.getElementById('nameLabel').innerHTML = "";
}
//Validating Phone Number Input
var phone = document.getElementById('phone').value;
phone = phone.toString();
if (document.getElementById('phone').value == null) {
document.getElementById('phoneLabel').innerHTML = "Required field! Enter your phone number.";
submitBool = false;
} else if (phone[3] != "-") {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else if (phone[7] != "-") {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else if (phone.length > 12 || phone.length < 12) {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else {
document.getElementById('phoneLabel').innerHTML = "";
}
//Form runs if input has been valid in all input options
if (submitBool == false) {
return false;
} else if (submitBool == true){
var preFixed = totalCost / 100;
var postFixed = preFixed.toFixed(2);
document.getElementById('totalcost').innerHTML = "Total Bill: $" + postFixed;
document.getElementById('submitMessage').innerHTML = "Order is being processed, <a>cancel?</a>"
setTimeout(function() {
return true;
}, 5000);
}
}
</script>
</html>
```
You can use the onSubmit event and delay the usual functionality. I've created a simple demo thus you can understand it easily. Here after form submission it'll submit the form after 5 seconds, or be canceled if you hit Cancel.
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', handleSubmit);
var submitTimer;
function handleSubmit(event) {
console.log('submitTimer set');
event.preventDefault();
submitTimer = setTimeout(() => {
this.submit();
console.log('Submitted after 5 seconds');
}, 5000)
};
function cancel(){
clearTimeout(submitTimer);
console.log('Submit Canceled');
}
<form id="myForm">
<input type="text" name="name"/>
<button type="submit">Submit</button>
<button type="button" onclick="cancel()" >Cancel</button>
</form>
The setTimeout function calls a function or evaluates an expression after a specified number of milliseconds (in your case 5000). What you did in your code was just to return a boolean without creating a channel to get the value after the time has lapsed. Since this code is sort of "asynchronous" (it takes time), you can use the inbuilt Promise function to get the value. In order words, your code could be restructured to something like this:
getTheBoolValue = () => new Promise((resolve, reject) => {
setTimeout(function(){
resolve(true)
},5000)
})
getTheBoolValue().then(data => console.log(data))

Cannot submit a form in html after loading the page

I am trying to submit a form in HTML after loading the page. It works when the form is refreshed. Otherwise, the form can't submit. My HTML page, complaint.html is below:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
<link rel="stylesheet" href="jquery.mobile-1.4.5/demos/css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="jquery.mobile-1.4.5/demos/_assets/css/jqm-demos.css">
<script src="jquery.mobile-1.4.5/demos/js/jquery.js"></script>
<script src="jquery.mobile-1.4.5/demos/_assets/js/index.js"></script>
<script src="jquery.mobile-1.4.5/demos/js/jquery.mobile-1.4.5.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script>
$(document).ready(function() {
$('#submt4').removeClass('ui-btn');
});
</script>
</head>
<body>
<div class="center container-fluid">
<div class="row">
<div class="col-xs-12">
<h2 align="center">COMPLAINTS</h2>
</div>
</div>
<div class="row">
<div class="col-xs-12"><input type="text" placeholder="Name" name="name" id="name">
</div>
</div>
<div class="row">
<div class="col-xs-12"><input type="text" placeholder="Mobile" name="mobile" id="mobile"></div>
</div>
<div class="row">
<div class="col-xs-12"><input type="text" placeholder="Vehicle No" name="vehicleno" id="vehicleno"></div>
</div>
<div class="row">
<div class="col-xs-12"><textarea rows="4" cols="50" name="complaint" id="complaint">Enter your complaint here...</textarea></div>
</div>
<div class="row">
<div class="col-xs-12" align="center">
<button class="btn btn-primary btn-lg " type="button" id="submt4" onClick="funComplaint();">SUBMIT</button></div>
</div>
</div>
</div>
<script type="text/javascript">
function funComplaint() {
var name = document.getElementById("name").value;
var mobile = document.getElementById("mobile").value;
var vehno = document.getElementById("vehicleno").value;
var complaint = document.getElementById("complaint").value;
var letters = /^[A-Za-z, ]+$/;
var numbers = /^[0-9]+$/;
var alphanum = /^[0-9a-zA-Z]+$/;
if (name == "" || mobile == "" || vehno == "" || complaint == "") {
alert("Please fill all fields........");
return false;
}
if (name.match(letters)) {} else {
alert("Name must have alphabet characters only");
document.getElementById('name').focus();
return false;
}
if (mobile.match(numbers)) {} else {
alert("Mobile number must have numeric characters only");
document.getElementById('mobile').focus();
return false;
}
if (mobile.length == 0 || mobile.length > 12 || mobile.length < 10) {
alert("Mobile number should not be empty / length be between 10 to 12");
document.getElementById('mobile').focus();
return false;
}
if (vehno.match(alphanum)) {} else {
alert("Vehicle number must have alphanumeric characters only");
document.getElementById('vehicleno').focus();
return false;
}
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
var msg = x.responseText.trim();
if (msg == "Complaint Received") window.location = "home.html";
} else {
alert(msg);
}
}
}
x.open("GET", "http://localhost:8087/CarRental/com/selcar/getComplaint.jsp?name=" + name + "&mobile=" + mobile + "&vehno=" + vehno + "&complaint=" + complaint, true);
x.send();
}
</script>
</body>
</html>
After x.onreadystatechange definition you have one too many }.
Just remove one } before x.open(....

Form validation not working on submit

After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
HTML:
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="lastName" hidden>שם משפחה</label>
<input type="text" name="lastName" id="lastName" class="cv form-control" placeholder="שם משפחה" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא" onkeyup='validateMessage()'>
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50" onkeyup='validateMessage()'></textarea>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button onclick='return validateForm()' class="btn btn-custom-outline " id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<br>
<!-- <div class="success"><?= $success ?></div>-->
<!--<span class="error"></span> -->
</form>
My JavaScript:
function validateName() {
var name = document.getElementById('name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false;
}
if (!name.match( /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i)) {
producePrompt('Letters only please.','name-error', 'red');
return false;
}
producePrompt('Valid', 'name-error', 'green');
return true;
}
function validatePhone() {
var phone = document.getElementById('phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false;
}
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false;
}
producePrompt('Valid', 'phone-error', 'green');
return true;
}
function validateEmail () {
var email = document.getElementById('email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false;
}
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false;
}
producePrompt('Valid', 'email-error', 'green');
return true;
}
/*function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 30;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false;
}
producePrompt('Valid', 'message-error', 'green');
return true;
}*/
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() ) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false;
}
else {
}
}
function jsShow(id) {
document.getElementById(id).style.display = 'block';
}
function jsHide(id) {
document.getElementById(id).style.display = 'none';
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
My scrips are in index.html , same page the form is, in the end :
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
<script src="js/bootstrap.min.js" ></script>
<!-- [ SLIDER SCRIPT ] -->
<script type="text/javascript" src="js/SmoothScroll.js"></script>
<script src="js/script.js" ></script>
<script src="js/validateform.js" ></script>
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
The issue that you are running into in calling
producePrompt('Email Invalid','email-error', 'red');
and any other where you are not passing name-error an error is occurring as there is no element with the id email-error they all have the same id. When the error is thrown the function returns undefined instead of false causing the form to be submitted.
When using Chrome dev tools you can go into settings and check preserve log this will allow you to see errors even after the page refreshes.
As to checking for all errors instead of just the first one...
the if (!validateName() || !validatePhone() || !validateEmail() ) {
or statements here mean the first one that false causes the rest to not be checked. Instead you could do something like the following
var vn = validateName();
var vp = validatePhone();
var ve = validateEmail();
if (!vn || !vp || !ve) {

Categories

Resources