Performing a Javascript validation to ensure that a value falls within

How can I check if an input number falls within a specified range? I need to display if it is within the range, higher, or lower than the acceptable range.

My current Javascript code seems to be causing an error message stating it is an invalid entry.

It should be able to handle decimal places, as the range values are user-defined.

    var highRange = 17.80;
    var lowRange = 6.90;
    var valueToCheck = (rText.value);

    function checkRange() {
        var msg = 'Invalid entry';
        if ((valueToCheck > 0.00) && (valueToCheck <= lowRange)) { msg = 'LOW'; }
        if ((valueToCheck > lowRange) && (valueToCheck <= highRange)) { msg = 'NORMAL'; }
        if ((valueToCheck > highRange)) { msg = 'HIGH'; }
        rangeValue = msg;
    }

I'm puzzled as to why it's not functioning properly, haha.

Any assistance would be greatly appreciated :-)

Answer №1

Give this a try.

    var highRange = 17.80;
    var lowRange = 6.90;
   

    function checkRange() {
       var valueToCheck = document.getElementById('rText').value;
        var msg = 'Invalid entry';
        if ((valueToCheck > 0.00) && (valueToCheck <= lowRange)) { msg = 'LOW'; }
        if ((valueToCheck > lowRange) && (valueToCheck <= highRange)) { msg = 'NORMAL'; }
        if ((valueToCheck > highRange)) { msg = 'HIGH'; }
        document.getElementById('rangeValue').innerHTML = msg;
    }
<input type="text" id="rText" >
<input type="button" value="Validate" onclick="checkRange()">
<p id="rangeValue"></p>
The issue was that the valueToCheck variable was placed outside the function, resulting in it getting a null value when the page loaded. To address this, the valueToCheck should be placed inside the function so it can accurately capture any changes in the input.

Answer №2

Convert your string to a float by using the parseFloat method.

var floatValue = parseFloat(inputText.value);

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

Error: The meteor package encountered a SyntaxError due to an unexpected reserved word 'export'

I've made some modifications to a meteor package by adding this line: export const myName = 'my-package' However, I'm encountering an error: export const myName = 'my-package' ^^^^^^ SyntaxError: Unexpected reserved word I ...

React.js: The specified element type is not valid:

I am currently working on a sample project using react.js in Visual Studio 2019 Here is my Index.js file: import 'bootstrap/dist/css/bootstrap.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provi ...

Creating a jQuery AJAX data object that contains numerous values for a single key

My goal is to make an ajax call with multiple values in the same key within the data object. var data = { foo: "bar", foo: "baz" } $.ajax({ url: http://example.com/APIlocation, data: data, success: function (results) { console.log(res ...

Modifying the scope variable does not trigger an update in the AngularJS directive

Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this: <layout name="Default">My cool content</layout> into this output: <div class="layoutDefault">My ...

Retrieve the content of a specific HTML tag using JavaScript

Is it possible to extract the content of a specific HTML tag as a string or XML format? <body> <script src="jquery.min.js"> //var test = document.getElementsByTagName("input"); //alert(test[0]); $(document).ready(function ( ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

Create a random number on the server every X interval

Context I have developed a Node.js application that generates a random number every 6 seconds and exposes it through an API. To maintain separation of concerns, I decided to encapsulate the number generation logic in a function called numberGen, stored i ...

Each time the website refreshes, Object.entries() rearranges the orders

After reading the discussion on Does JavaScript guarantee object property order? It seems that Object.entries() should maintain order. However, I encountered an issue with my Angular website where the order of keys in Object.entries() changed upon refres ...

Extending fabric.js toObject with custom properties can result in the loss of default properties

After doing extensive research on various platforms, including this one, I am still struggling to get everything working as desired. My main goal is to save custom properties in all shapes, specifically the uuid and rt_attributes. Following the manual, I ...

Issue encountered: Unable to locate module: Error - Unable to resolve '@cycle/run' with webpack version 2.2.1

I am attempting to run a hello world application using cycle.js with webpack 2.2.1. The following error is being displayed: ERROR in ./app/index.js Module not found: Error: Can't resolve '@cycle/run' in '/Users/Ben/proj/sb_vol_cal ...

An external script containing icons is supposed to load automatically when the page is loaded, but unfortunately, the icons fail to display

Hello and thank you for taking the time to read my query! I am currently working in a Vue file, specifically in the App.vue where I am importing an external .js file containing icons. Here is how I import the script: let recaptchaScript2 = document.creat ...

Pass the initial value from a parent component to a child component in ReactJS without the need for state management

Initially, I have a parent Component A that calculates an initial value for its child Component B. The initial value is computed in the componentDidMount() of Component A and passed to B using props: <ComponentB initialValue={this.state.value} handleCha ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

Guide to Incorporating a Marker into an SVG Blinking Rectangular or Circular Border Image on Google Maps

I have a link that points to a specific location on Google Maps using latitude and longitude: http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png Now, I am looking to add a blinking border to this marker link. Is there a way to achieve this ...

Upon running the command "React + $ npm start," an error occurred with the code 'ERR_OSSL_EVP_UNSUPPORTED' related to opensslErrorStack

When running $npm start, an error is being thrown: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_ ...

The occurrence of the "contextmenu" event can cause disruption to the execution of a function triggered by the "onmousemove" event

Currently in the process of developing a Vue application utilizing a Pinia store system. Within my BoxView.vue component, I have created a grid layout with draggable elements that have flip functionality implemented within the BoxItem.vue component. Spec ...

Utilizing Supabase queries alongside React's Hot Toast Promise: A Comprehensive Guide

I'm currently working on an admin panel to manage my website. As part of the development, I am using Supabase for the Database and React Hot Toast for notifications. Recently, I attempted to implement Toast Promise using the following code: const add ...

Ways to customize decoration in Material UI TextField

Struggling to adjust the default 14px padding-left applied by startAdornment in order to make the adornment occupy half of the TextField. Having trouble styling the startAdornment overall. Attempts to style the div itself have been partially successful, b ...

The equivalent of an event listener in event handling

Here is an example of how to set up event listeners: document.getElementById("A").addEventListener("change", function (e) { // do something when A changes }, false) document.getElementById("B").addEventListener("click ...

What benefits does registering a Vue component locally provide?

According to the Vue documentation, global registration may not always be the best option. The documentation states: Global registration is not always ideal. When using a build system like Webpack, globally registering all components can result in unnece ...