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

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

Using jQuery, how can I dynamically change the stacking order of an element when clicked?

I'm struggling to change the z-Index on button click. I have a static image and a dynamic div, and I want to send the #imgDiv1 behind the static image. Unfortunately, despite trying everything, I haven't been able to achieve this. You can check ...

Using THREE.js: Object3D Dimension Shrinkage

Is there a way to disable sizeAttenuation for an Object3D in THREE.js? I'm working on rendering a trajectory at a massive scale using arrow helpers to show the motion direction. I want the arrow heads to maintain their orientation without changing si ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...

Can a website accurately identify my operating system and browser version even if my browser settings have been altered?

When using selenium to browse a website, I have modified the useragent, platform, and oscpu properties of the navigator object in my Firefox browser. Will the website be able to detect my actual operating system and browser version? ...

What is the best way to dynamically add getJSON's data to a div whenever the loadmore button is clicked?

When a page loads, my getJSON function displays its output in a div called myDiv. Now, I am looking to add a button at the bottom of the page. When the user clicks this button, I want to trigger another call to getJSON. Each time the button is clicked, I ...

Develop a JavaScript application that contains a collection of strings, and efficiently sorts them with a time complexity of O(nlog n)

Seeking assistance in developing a JavaScript program that contains an array of strings and must sort them efficiently in O(nlog n) time. Grateful for any guidance... ...

Create line items using the quantity code as a reference

I need help implementing a feature that dynamically adds line items based on user input in a quantity text box. For example, if the user enters a quantity of 2, the page should display: Text line for item 1 Text line for item 2 Here is the code snippet ...

Instructions on how to insert a new row into Datatables following the successful submission of a form via AJAX请求

Could someone please provide guidance on how to insert a new row into an existing datatable after a successful AJAX request? Here is the code I am currently using: $(document).ready(()=>{ $.ajax({ url: 'http://localhost:3000/api/post/getUserDat ...

The jquery script for the dynamic remove button is malfunctioning

I have successfully implemented code to display dynamic controls using jQuery. Below is the working code: <script type="text/javascript"> $(document).ready(function() { $("input[value='Add']").click(function(e){ e. ...

When a User registers, they are successfully added to the database. However, upon inspection in the browser, the JWT token appears as "undefined."

My goal is to successfully register a user and then ensure that a token persists in the browser. Currently, the user gets registered and added to the database but I am facing some issues. When inspecting, I notice that there is no token (token: "undefined" ...

Learning how to interpret input from the command line in Vertx

Would appreciate some guidance on how to read command line arguments in vert.x using JavaScript. For instance, I am wondering how to go about reading: arguments(arg1, arg2, arg3) vertx run example.js arg1 arg2 arg3 ...

What are some ways to create a responsive image design?

Currently, I am using the code below to enlarge an image when clicked on. I have attempted using media queries in CSS... I have also added another class in #modalPopupHtml# to adjust the size of the large image: .imgsize{ height: 600px; width: 800px; ...

When trying to convert a function component to a class component, using `npm init react-app` may result in the error `ReferenceError: React is not defined no-undef`

After running npm init react-app appname, I noticed that the file App.js was created, containing a function component: function App() { return ( <SomeJSX /> ); } I decided to change this function component into a class component like this: c ...

Tips on utilizing the enter key to add my <li> element to the list?

Currently, my to-do list setup requires users to click a button in order to add a new list item. I am looking to enhance the user experience by allowing them to simply hit "enter" on their keyboard to achieve the same result. Here is the JavaScript code I ...

Error: Trying to access the length property of an undefined or null reference in JSON formatted data fetched through Ajax

I am attempting to populate a jQuery DataTables with JSON data retrieved from a Web API ajax call, but encountering the following error: An unhandled exception occurred at line 38, column 314 in 0x800a138f - JavaScript runtime error: Unable to get proper ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

Using the integrated pipeline mode in IIS is necessary for this operation to be

My aspx page has an ajax call which looks like this: $.ajax({ url: "/SiteAdmin3/UpsIntegration.aspx/addUpdatePackageData", data: JSON.stringify({ '_OrderNumber': $("#txtOrderNumber ...

Utilizing the identical modal for Add/Edit functionality within AngularJS

Recently, I started working with AngularJS and I am in the process of creating a simple project that involves creating, reading, updating, and deleting countries. The code is functioning correctly overall. However, I have encountered an issue regarding th ...

Steps for adding an onclick function to a collection of div elements

My current project involves utilizing the Flickr API and I am interested in creating a popup div that opens when clicking on each image. The goal is to display the image in a larger form, similar to how it's done using Fancybox. I'm looking for ...