Ensuring the validity of float and non-empty values in JavaScript

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.

Answer №1

To quickly solve the issue, change 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"
        />

Modify the validation function as shown 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;
}

Answer №2

Modify the following code snippet:

function verify() {
if(value1 == "" || value2 == "")
    return false;
return true;

}

with this updated version:

function verify() {
if(value1.value == "" || value2.value == "")
    return false;
else
    return true;
}

This revised code should be effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery script version 3.5.1 encountered an error at line 4055 where DataTables was unable to access the property "aDataSort" due to it

Hey there, I'm currently facing a small challenge while trying to incorporate Datatables within a bootstrap modal to display the results of a SQL Server query. The main requirement is to provide the option to export the data as an Excel file or in oth ...

Eliminate the need for require statements in TypeScript-generated JavaScript files

I am working on a website project and utilizing TypeScript for development. While using the tsc compiler, I noticed that all my JavaScript code compiles correctly. However, when I include an import statement in my TypeScript files, it gets compiled into J ...

Troubleshooting $templateCache not functioning correctly within the Angular.js angular-config

I keep encountering an error message that says "angular.min.js:6Uncaught Error: [$injector:modulerr]" whenever I try to implement $templateCache in my app.config block. Interestingly, when I remove the $templateCache parameter from app.config, the errors d ...

Deleting an item in Vue.js with the removal feature

After deleting items from my list, they remain visible until I manually refresh the page. How can I fix this issue? List <tbody> <tr v-for="school in schools" v-bind:key="school.id"> <td>{{ school.id }}</td> &l ...

Display of items in a submenu through a drop-down menu when hovering over it

As I work on creating a Navbar with a dropdown menu, I'm encountering an issue where hovering over the main list element displays all the submenu contents at once. No matter what I try in my CSS, including adjusting the positioning of li and ul elemen ...

The character is having trouble displaying correctly in the ajax response

I've been searching for solutions but nothing seems to help. The issue I'm facing is with reading characters from an AJAX response. How can I properly read characters that are coming from an AJAX response in the form of a JSON object? ["label" ...

Display the iframe website without it being visible to the user

Is there a way to load a separate website, such as a Wikipedia article, in an iframe on a webpage without freezing up the whole page when it becomes visible after clicking a "show" button? And if not, how can we display a loading gif while the iframe is ...

The functionality of Angular bootstrap scrollspy is hindered when dealing with dynamically changing image content

I recently came across an answer that guided me to fork an example for implementing scrollspy in Angular.js. My goal is to populate dynamic content using a template that includes images. You can find the example here: http://plnkr.co/edit/OKrzSr Here are ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

Does the AppBar stay consistent throughout the entire Page Control in Metro Apps?

Having trouble making the AppBar stay constant on my Metro app webpage. Whenever I click on other items, the AppBar disappears. Any tips on how to keep the AppBar visible for the entire page in my Metro App? I am currently using appbar.winControl.show(); ...

Guide on making a button for adding products to the shopping cart

I have put together this web page Check out the views.py code below: from django.shortcuts import render from django.http import HttpResponse from .models import Pizza # Managing views here. def index(request): pizzas = Pizza.objects.all().order_by( ...

Is there a way to shut down a browser tab without being asked, "Are you sure you want to close this window"?

Is there a way to gracefully close a browser window without being interrupted by the annoying Do you want to close this window prompt? I've noticed that whenever I attempt to use the window.close(); function, this prompt always pops up. ...

Can an unordered list be nested inside an inline list item in HTML or XHTML?

Take note that the li with child ul is set to display:inline - example code provided below <style type="text/css"> ul.nav_main li { display: inline } ul.nav_submenu li { display: block } </style> <ul class="nav_main"> <li>I ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

Changing the CSS of ng-view when triggering CSS in ng-include: A step-by-step guide

Incorporating my left-hand, vertical navbar into the page using ng-include, I've managed to make it expand right on hover. Each page is enclosed within a <div class="wrapper">. My goal is to adjust the margin of each wrapper as the navbar expan ...

Setting the flex-direction for <td> elements: A helpful guide

This is a snippet from the render function of one of my components, showcasing a table: return ( ... <td> <div style={{ width: '100%' }}>50</div> {' '} <span clas ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

What exactly is HTML cloud storage all about?

As I work on developing an app through phonegap, one question that comes to mind is the possibility of storing information online. For instance, if there's a number variable that increases when a button is pressed, can this value be saved somewhere an ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...