Exploring the possibilities of using the typeof operator within an Event

I want to log some information if the input value is a number. However, I am facing an issue where it's not working and no bugs are appearing.

Here is a snippet of code from CodePen (https://codepen.io/matoung/pen/KBNmPP)

let button = document.querySelector('.buttonClass');


button.addEventListener('click', function() {
    let myValue = document.querySelector('.inputClass').value;
    if(typeof myValue === 'number'){
        console.log('This is a number');
    }
});
.wrapper {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
}

.container-6 {
    border: 1px solid #000;
    align-items: center;
    padding: 40px;
    margin-top: 100px;
}
<html>
<head>
<title>Random</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
</head>
<body>
<input type="text" class='inputClass' />
<input type="button" value="Send" class="buttonClass"/>
<div class="wrapper">
<div class="container-6">
<p>It will be a number</p>
</div>
<div class="container-6">
<p>It will be a string</p>
</div>
<div class="container-6">
<p>It will be a boolean</p>
</div>
<div class="container-6">
<p>It will be an array</p>
</div>
<div class="container-6">
<p>It will be an undefined</p>
</div>
<div class="container-6">
<p>It will be a null</p>
</div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Answer №1

To verify if a value is a number, you can utilize the isNaN function.

let button = document.querySelector('.buttonClass');

button.addEventListener('click', function() {
    let myValue = document.querySelector('.inputClass').value;
    
    if(!Number.isNaN(parseInt(myValue))){
        console.log('This is a number');
    }
});
.wrapper {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
}

.container-6 {
    border: 1px solid #000;
    align-items: center;
    padding: 40px;
    margin-top: 100px;
}
<html>
<head>
<title>Random</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
</head>
<body>
<input type="text" class='inputClass' />
<input type="button" value="Send" class="buttonClass"/>
<div class="wrapper">
<div class="container-6">
<p>It will be a number</p>
</div>
<div class="container-6">
<p>It will be a string</p>
</div>
<div class="container-6">
<p>It will be a boolean</p>
</div>
<div class="container-6">
<p>It will be an array</p>
</div>
<div class="container-6">
<p>It will be an undefined</p>
</div>
<div class="container-6">
<p>It will be a null</p>
</div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Answer №2

Hari has already provided a correct response. However, if you wish to identify more than just number data types, you can utilize JSON.parse as shown below:

button.addEventListener('click', function() {
    let inputValue = document.querySelector('.inputClass').value;

    try {
        inputValue = JSON.parse(inputValue);
    } catch (error) {
        // The input value does not contain valid JSON, indicating it may be any random string.
        // You can define what counts as 'undefined' here.
    }

    if (typeof myValue === 'number'){
        console.log('This is a number');
    } else if (typeof myValue === 'boolean') {
        console.log('This is a boolean');
    } // and so on
});

Answer №3

To check if a value is a number in JavaScript, you can utilize the unary plus operator along with parseFloat and isNaN.

Here's an example:

let number = +myValue;
if (number === parseFloat(myValue) && !isNaN(number)) {
  // If it's a number, you can use the 'number' variable
}

This approach incorporates all three methods to handle various scenarios:

  1. The parseFloat function converts up to the first non-numeric character, ensuring values like '12.10px' are parsed correctly as '12.10'.
  2. The unary plus operator transforms an empty string "" into 0, catering to cases where parseFloat returns NaN, which is expected behavior.
  3. If both of the previous steps result in NaN, the isNaN function is used to prevent false positives.

While this method covers most scenarios, note that JavaScript considers strings like '0x10' (hexadecimal) and '0.0314E+2' valid numbers. For strict floating-point validation such as '00.0', a regular expression can be more suitable:

if (/^\d*\.?\d+$/.test(myValue)) {
  // It's a number, then convert using the unary operator
  let number = +myValue;
}

For integers only, a simpler regexp like '/^\d+$/' suffices.

I hope this explanation clarifies things for you!

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

Guide on making an AJAX post request to a modified URL

I am currently facing an issue where I am unable to submit a form to a PHP file via post method due to some problem with ajax. My query is, can I submit the form to a different URL if the backend has rewritten URLs? CURRENT PAGE URL: - actual: - re-wri ...

Tips for using ng-repeat in AngularJs to filter (key, value) pairs

I am trying to achieve the following: <div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div> Code snippet for AngularJs: function TestCtrl($scope) { ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

What is the best way to set a newly selected HTML option as the first choice?

I'm facing a simple problem in JavaScript that I can't seem to crack. Admittedly, I am new to working with JavaScript. My issue lies with sorting a dropdown list in alphabetical order while also keeping the selected value at the top. Whenever a ...

The route is displaying the variable as 'undefined' when I attempt to access it

I had set up CRUD for two different models (venues & artists) - venues works fine, but when I try to access 'artists/index', it gives me an error saying 'Artists is not defined'. After examining the code, I believe I need to do two ...

Tips on showing binary information as images using extjs 4

As the proud owner of a valid .JPEG image's binary data, I am on a quest to convert this information into an actual viewable image using Python. Seeking advice on how to successfully transform this binary code into a visually appealing .JPEG format w ...

Connecting Angularfire2 with Firestore for advanced querying

Glad you stopped by! Currently, I have two Firestore Collections set up in my Angularfire2 application. One consists of "Clients", while the other contains "Jobs". Each client can have multiple jobs assigned to them, and vice versa. I've been workin ...

Creating a dynamic search bar with multiple input fields in HTML

My JSON input for typeahead looks like this: [{"q": "#django", "count": 3}, {"q": "#hashtag", "count": 3}, {"q": "#hashtags", "count": 0}, {"q": "#google", "count": 1}] This is the code I have to implement typeahead functionality: var hashTags = new Blo ...

The issue of unselection not functioning properly for multiple items when using both selectable and draggable features

i need the unselection of list items to be as smooth as selectable() but without draggable() My desired outcome is similar to the following gif showcasing combined selectable and draggable functionality: https://i.stack.imgur.com/3GjTD.gif here's t ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

Step-by-step guide on how to have an AngularJS controller run continuously every 5 seconds once it has been initially called

My angular js file (app.js) contains the uuidCtrl controller, which triggers when called. When I want to call the controller 2 times, I have to load the page twice. However, I am looking for a solution to run it continuously after the first time it is call ...

The plugin function cannot be executed unless inside the document.ready event

Utilizing jquery and JSF to construct the pages of my application includes binding functions after every ajax request, such as masks and form messages. However, I am encountering an issue where I cannot access the plugins outside of $(function(). (functio ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...

Looking to generate an HTML table using JavaScript?

Similar Question: Create HTML table from a Javascript array I have received an array that looks like this var univArray = new Array( {name: "Stanford University", nick: "Stanford", ownership: "private", sys: "n/a", SATh: 1550, SATl: 1360, tui ...

Tips for implementing a repeater item to function beyond the ng-repeat directive

Recently, I decided to play around with AngularJS and now I seem to be facing a small issue with ng-class. Specifically, I'm attempting to change the color of an awesome font icon. <div ng-controller="MyCtrl"> <i ng-class="{'test': ...

Updating the active color for Material UI Input elements

I'm having trouble changing the color of an active input field. I want to customize it with my theme's primary color, but I can't figure out how to do it. I've tried adjusting the color attribute in various components like FormControl, ...

Address Book on Rails

Hello, I'm relatively new to this and would be grateful for any assistance. My goal is to utilize the data saved by a user in their address book, and then offer them the option to use that address for delivery. Below is my Address controller: class A ...

`In NodeJS, facing a challenge with implementing a many-to-many relationship using Sequelize's

I'm in the process of setting up many-to-many relationships between roles and accesses. The `roles` table will contain a list of roles (admin, developer, etc...) and the `accesses` table will have a list of permissions (Create Project, Create Site, De ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

.fetchevery(...).then has no function

I recently upgraded Angular to version 1.6.4. As a result, I made changes to the code by replacing .success and .error with .then However, now I am encountering the following error: An unexpected TypeError occurred: .getAll(...).then is not a function ...