Embarking on the journey of web development, I'm delving into basic applications. My current project involves creating a straightforward webpage to add two numbers and implementing preliminary validations - ensuring that the input fields are not left empty and only accepting float numbers.
The structure of my index.html file:
<!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.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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3b3acb3b3a6b1eda9b083f2edf2f5edf3">[email protected]</a>/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 JavaScript script, found in 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");
}
}
Unfortunately, the JavaScript code isn't functioning as expected with regards to validation and summation.