How to delay form submission - javascript

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

Related

When I hit the submit button, I'm unable to achieve the, "Enjoy your day" on the entire screen after one or all the checkboxes have been checked

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Checklist</title>
<link rel="stylesheet" type="text/css" href="./style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit"
onchange="document.getElementById('formName').submit()">
</div>
<!--<p id="msg"></p> (I tried using this approach and calling the msg within script but I received an error.)-->
</form>
</div>
</body>
<script>
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
var submit = document.getElementById('submit');
var text = document.getElementById('msg');
//My if/else statement alert works perfectly. However, with the presence of const submit, it doesn't work properly (I think it's interfering with my if/else statement). Removing the const submit section allows one to experience the if/else alert statement. The goal of this checklist is to be able to check one or all four checkboxes and have it return the "Enjoy your day" text. However, I would like for that message to cover the screen and be the only thing visible after hitting the submit button. I'm okay with receiving an alert box when it returns false. However, when it returns true, I would like for the message to cover the screen and for the checklist/checkboxes to disappear. I'm not sure where I'm getting my wires crossed.
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
} else {
return true;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
}
</script>
</html>
enter image description here
enter image description here
You are declaring submit twice in the isChecked function. Omit one of the declaration.
Also, you are adding the event listener to the submit button after the return statement, which JS will ignore and won't append any onclick function.
The updated isChecked function should be
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
// Removed the submit variable
var text = document.getElementById('msg');
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
// Returning true after adding the event listener.
return true;
}
Just display the message since it is being called onsubmit
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
if (!workout && !meeting && !lunch && !school) {
alert('Please check a box');
} else {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
}
return false;
}
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit">
</div>
</form>
</div>

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.

Bug in JQuery function for checking for required fields in custom dropdowns

I made a JQuery function to check for empty required fields inside a closed custom dropdown.
If a required field is empty inside one of the dropdown and if the dropdown is currently closed I want the dropdown to open and if there are no empty values in the required fields I want the dropdown to close.
The problem is that the required fields aren't accessible if the dropdowns are closed and I tried to fix that problem with this function.
For some reason, it only checks for these input fields if the form is submitted at least once and the required fields are opened at least once.
find(':input[required]') doesn't give any output if the dropdown isn't opened at least once, once u open and close the dropdown the function works.
This is the function:
function dropdown_required() {
var required = 0;
$('#visible_fields').find(':input[required]').each(function () {
if (!this.value) {
for (var i = 1; i < 15; i++) {
$('.form_' + i).find(':input[required]').each(function () {
$(this).prop('required', false);
});
}
required++;
}
});
if (required == 0) {
for (var i = 1; i < 15; i++) {
var empty = 0;
$('.form_' + i).find(':input[required]').each(function ()
{
if(!this.value) {
empty++;
}
});
if (empty !== 0) {
if ($(".arrow_" + i).hasClass("rotate_2")) {
$(".arrow_" + i).addClass("rotate_1").removeClass("rotate_2");
$(".form_" + i).fadeToggle();
}
} else if ($(".arrow_" + i).hasClass("rotate_1")) {
$(".arrow_" + i).addClass("rotate_2").removeClass("rotate_1");
$(".form_" + i).fadeToggle();
}
}
}
}
This is the html:
<form method="POST" autocomplete="off" enctype="multipart/form-data" target="_self"
action="/contacten/leveranciers/iframe{{ ($leverancier == null ? '' : '/' . $leverancier->cot_id) }}">
{{ csrf_field() }}
<div id="visible_fields">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="organisatie">Organisatie</label>
<input type="text" name="organisatie" id="organisatie" blocked=",;()/" hk="a"
value="{{ ($leverancier == null ? old('organisatie') : $leverancier->cot_organisatie) }}"
class="form-control inputblocked">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" id="postcode" filter="a-zA-Z0-9" maxlength="6"
value="{{ ($leverancier == null ? old('postcode') : $leverancier->cot_postcode) }}"
class="form-control inputfilter filter_postcode">
</div>
</div>
</div>
//all visible input fields outside of the dropdowns
</div>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="bkr">BKR</label>
<select name="bkr" class="form-control" required>
<option selected hidden></option>
<option value="10">BKR toetsing open</option>
<option value="11">BKR toetsing accoord</option>
<option value="12">Vrijgesteld van BKR toetsing</option>
</select>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="bkr_bestand">BKR bestand</label>
<input type="file" name="bkr_bestand" id="bkr_bestand"
data-default-file=""
class="form-control dropify">
<input type="hidden" name="verwijder_foto" class="verwijder_foto" value="0">
</div>
</div>
</div>
</div>
<div class="form-group">
<input type="hidden" id="input_iframe" name="input_iframe" value="">
<button type="submit" onclick="dropdown_required()"
class="btn btn-primary">Toevoegen </button>
</div>
</form>
</div>
</body>
</html>
Your function checks if your arrow element has the class rotate_2. The code you pasted has neither rotate_1 or rotate_2 and no else block, so the toggle never executes.
Problem demonstration:
// This group has empty mandatory elements
var empty = 1;
$('#validate').click(function() {
if (empty !== 0) {
console.log("I have empty elements!");
// From your comments, this might be backwards
if ($(".arrow_1").hasClass("rotate_2")) {
console.log("I'm going to show them");
$(".arrow_1").addClass("rotate_1").removeClass("rotate_2");
$(".form_1").fadeToggle();
}
// This is missing in the code
else {
console.log("I wasn't invited to the party");
}
// -------
} else if ($(".arrow_1").hasClass("rotate_1")) {
console.log("I'm out, I don't have empty elements...");
$(".arrow_1").addClass("rotate_2").removeClass("rotate_1");
$(".form_1").fadeToggle();
}
});
$('#simulate').click(function() {
// Simulates manually opening and closing
// In short, add rotate_2 class as if it's been toggled
$('.arrow_1').addClass('rotate_2');
console.log("Toggled manually");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div>Some form elements</div>
</div>
<button id="validate">Validate</button>
<button id="simulate">Simulate</button>

how dynamically add new button by javascript

I have two textboxes and one button,
I want to add one new textfield, that should show card name from textbox1 and Link URL append from textbox2 when I click on button
//AddnNewCardNavigator
var counter=2;
var nmecardtxt= document.getElementById("textbox1").value;
var linkurltxt= document.getElementById("textbox2").value;
$("#addbutton").click(function(){
if(nmecardtxt ==""||nmecardtxt ==0||nmecardtxt ==null
&& linkurltxt ==""||linkurltxt ==""|| linkurltxt ==0||linkurltxt ==null){
alert("Please insert value in Card name and Link Url textboxes and must be correct");
return false;
}
var NewCarddiv = $(document.createElement('div')).attr("id",'cardlink'+counter);
NewCarddiv.after().html()
})
</script>
<!-- text boxes-->
<div class="row">
<div class="col-md-12">
<div id="textboxesgroup">
<div id="textboxdiv1">
<label style="color:blanchedalmond">Card Name: </label><input type="textbox" id="textbox1">
</div>
<div id="textboxdiv2">
<label style="color:blanchedalmond">Link Url:    </label><input type="textbox" id="textbox2">
</div>
</div>
</div>
</div>
Your variables nmecardtxt and linkurltxt must be created inside the click function,
because it's empty at the loading of the page.
I also took the liberty to use jQuery for that variables, as you're already using it, and tried to enhance some other things:
(See comments in my code for details)
//AddnNewCardNavigator
var counter = 2;
// On click function
$("#addbutton").click(function() {
// Here it's better
var nmecardtxt = $("#textbox1").val();
var linkurltxt = $("#textbox2").val();
// Modified you test here
if (!nmecardtxt || !linkurltxt) {
alert("Please insert value in Card name and Link Url textboxes and must be correct");
return false;
}
// Modified creation of the card
var link = $(document.createElement('a')).attr("href", linkurltxt).html(linkurltxt);
var NewCarddiv = $(document.createElement('div')).attr("id", 'cardlink' + counter).html(nmecardtxt + ": ").append(link);
$('#cards').append(NewCarddiv);
//NewCarddiv.after().html(); // Was that line an attempt of the above ?
});
body {
background: #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- text boxes-->
<div class="row">
<div class="col-md-12">
<div id="textboxesgroup">
<div id="textboxdiv1">
<label style="color:blanchedalmond">Card Name: </label><input type="textbox" id="textbox1">
</div>
<div id="textboxdiv2">
<label style="color:blanchedalmond">Link Url:   </label><input type="textbox" id="textbox2">
</div>
</div>
</div>
</div>
<!-- Added the below -->
<div id="cards">
</div>
<button id="addbutton">Add…</button>
Hope it helps.
Here's a simplified version of what you're trying to accomplish:
function addNewCard() {
var name = $('#name').val();
var url = $('#url').val();
var count = $('#cards > .card').length;
if (!name || !url) {
alert('Missing name and/or URL.');
}
var card = $('<div class="card"></div>').html("Name: " + name + "<br>URL: " + url);
$("#cards").append(card);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="url">URL:</label>
<input type="text" id="url" name="url">
<input type="submit" value="Add Card" onclick="addNewCard();">
<div id="cards">
</div>

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

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

Categories

Resources