Ensuring the validity of input tags

I encountered an issue with an input tag that has a specific logic:

https://codepen.io/ion-ciorba/pen/MWVWpmR

In this case, I have a minimum value retrieved from the database (400), and while the logic is sound, the user experience with the component leaves much to be desired. As it currently stands, users are unable to enter values below 400, which can be frustrating. I am looking for a way to improve the interaction without restricting the user from typing. Are there alternative methods besides just using 'change' and 'input' events? How can I enhance this interaction to be more user-friendly while still respecting the minimum value of 400?

Perhaps a better approach would be:

if (numberInputValue == "" || parseInt(numberInputValue) < parseInt(min)) {
numberInputValue = min;
} else if (parseInt(numberInputValue) > parseInt(max)) {
numberInputValue = max;
}

Answer №1

I am in agreement with @Twisty that the jQuery UI Slider would be a more suitable choice

$(function() {
  let slider = $(".tbi-slider")[0];
  let loanAmount = $(".tbi-calc-loanAmount");
  let totalLoanAmount = $(".tbi-calc-loanTotalAmount");
  var min = $(".tbi-slider").attr("min");
  var max = $(".tbi-slider").attr("max");
  $("#co-tbi-loanAmount-input").change(function(s) {
    var numberInputValue = s.target.value;
    if (numberInputValue.match(/^[0-9]+$/) == null) {
      $("#co-tbi-loanAmount-input").val(min);
    }
    slider.value = parseInt(numberInputValue);
    if (parseInt(numberInputValue) < parseInt(min)) {
      $("#co-tbi-loanAmount-input").val(min);
    } else if (parseInt(numberInputValue) > parseInt(max)) {
      $("#co-tbi-loanAmount-input").val(max);
    }
    if (
      parseInt(numberInputValue) >= parseInt(min) &&
      parseInt(numberInputValue) <= parseInt(max)
    ) {
      $("#co-tbi-loanAmount-input").val(numberInputValue);
    }
    $("#tbi-range-slider").slider("value", $(this).val());
  });

  $("#tbi-range-slider").slider({
    min: 400,
    max: 1000,
    orientation: "horizontal",
    range: "min",

    slide: function(event, ui) {
      refreshSwatch(),
        $("#co-tbi-loanAmount-input").val(ui.value);
    },

  });
});

function refreshSwatch() {
  $("#tbi-range-slider").css("background-color", "#729fcf");
}
body {
  font-family: system-ui;
  background: #f06d06;
  color: white;
  text-align: center;
}

#tbi-range-slider {
  display: inline-block;
  width: 300px;
  margin: 15px;
  background-image: none;
}

#tbi-range-slider .ui-slider-range {
  background: #ef2929;
}
<input id="co-tbi-loanAmount-input" class="tbi-calc-loanAmount co-tbi-input tbi-font-18" value="400">


<div class="tbi-slider" id="tbi-range-slider" min="400" max="1000" value="500"></div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>

<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

I trust this information is helpful

Answer №2

Consider the following.

$(function() {
  function checkValue(input) {
    // sanitize for Numbers Only
    if (isNaN($(input).val())) {
      return false;
    }
    // cast to Integers
    var val = parseInt($(input).val());
    var min = parseInt($(input).data("min"));
    var max = parseInt($(input).data("max"));
    console.log(val, min, max, (val >= min) && (val <= max))
    // return val is in between Min & Max
    return (val >= min) && (val <= max);
  }

  // Initialize Min & Max on Text Input as Data Attributes
  $("#co-tbi-loanAmount-input").data({
    min: $("#tbi-range-slider").attr("min"),
    max: $("#tbi-range-slider").attr("max")
  });

  $('#co-tbi-loanAmount-input').change(function(s) {
    // ignore 1, and 10, will start to look at 100
    if ($(this).val().length >= 3) {
      if (!checkValue(this)) {
        console.log("Incorrect Value: " + $(this).val());
        $(this).val("");
      } else {
        var numberInputValue = Math.floor(parseInt($(this).val()) / 100) * 100;
        $(this).val(numberInputValue);
        var start = parseInt($("#tbi-range-slider").val()) - parseInt($("#tbi-range-slider").attr("min"));
        var diff = parseInt($("#tbi-range-slider").attr("max")) - parseInt($("#tbi-range-slider").attr("min"));
        console.log("linear-gradient(to right, #FF6600 0%, #FF6600 " + Math.round(start / diff * 100) + "%, #DEE2E6 " + Math.round(start / diff * 100) + "%, #DEE2E6 100%)");
        $("#tbi-range-slider").val(numberInputValue).parent().css("background", "linear-gradient(to right, #FF6600 0%, #FF6600 " + Math.round(start / diff * 100) + "%, #DEE2E6 " + Math.round(start / diff * 100) + "%, #DEE2E6 100%)");
      }
    }
  });

  $("#tbi-range-slider").change(function() {
    $('#co-tbi-loanAmount-input').val($(this).val()).trigger("change");
  })
});
body {
  font-family: system-ui;
  background: #f06d06;
  color: white;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="co-tbi-loanAmount-input" class="tbi-calc-loanAmount co-tbi-input tbi-font-18" value="25000">
<div>
  <input type="range" min="400" max="50000" value="25000" step="100" class="tbi-slider" id="tbi-range-slider">
</div>

This feature allows users to input a number (e.g., 200, 400, 420, 10000) and adjust the slider accordingly if it falls within the range set by min and max.

If a user inputs the value of 200, it will be cleared. If they enter a non-numeric character like 'A', the value will also be removed.

If the user enters 420, it will be rounded down to 400.

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

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...

There seems to be a glitch in the functionality of annotations when using annotator.js

Currently, I am utilizing annotator.js to store the range in mysql. The following code fragment is being used for highlighting text within my file: <script src="/js/pdfjs/annotator.js"></script> <script> $(function(){ var annotation ...

Dynamic divs to occupy the rest of the available vertical area

I have been experimenting with a new website layout and created a form setup. However, I am facing an issue with the fluidity of the layout. While the items are floating into position, there is a problem where if the item on the right is 400px bigger than ...

Accessing a variable outside of the component constructor will result in the variable being

Currently, I am tackling a project that involves React and Electron. However, I have encountered an error that is causing some confusion. The issue revolves around a component with a constructor that receives props in the form of two variables. This constr ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

AngularJS Get request unable to fetch image URL due to receiving a "302 found" error

Trying to enhance my AngularJS app by incorporating an image from a random cat image site, using the URL received. Below is the snippet from my controller.js: 'use strict'; /* Controllers */ var catPath = "http://thecatapi.com/api/images/get? ...

Using jQuery to create a flawless animation

I am currently working on an animation project, and I have shared my progress on jsfiddle. Below is the code snippet I have utilized: /* JavaScript: */ var app = function () { var self = this; var allBoxes = $('.box&apos ...

Tips for correcting boolean checks and verification for undefined variables

Currently, I am working on a code where I need to verify the truthfulness of variables $scope.bankregel and $scope.showInvoices. Within my function, I'm already implementing a conditional check in the if and else if statements. How can I incorporate ...

Enhancing leaflet popup functionality by incorporating ng-click into the onEachFeature function

After creating a map and connecting it with my geojson api, I encountered an issue when trying to link each marker popup with ng-click. Simply adding HTML like this did not work as expected: layer.bindPopup("<button ng-click='()'>+feature. ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

Having Trouble Operating Virtual Tour in Flash

I recently used a third-party software to create a virtual tour for my client's website. The virtual tour works perfectly fine on its own, as you can see here: However, when I tried to include the virtual_tour.html page on the index page of the websi ...

What is the process for designing custom width columns using Bootstrap?

I am working on a table with three columns that is styled using the Bootstrap class "table table-striped". However, I need the first column to be 100px in width, the second column to be 400px, and the third column to be 200px. How can I achieve this cust ...

Using Ajax for updating table content on a JSP webpage section

I am working on implementing Ajax functionality for a table to enable partial updates every hour. Below is a snippet of my JSP code: < head > < meta http - equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < titl ...

How can you effectively utilize Selenium to web scrape a webpage featuring collapsible fields?

Have you checked out this website - ? I'm currently working on extracting fixture data from it, such as competition names, team names, and dates. Although I have a scraping solution in place, the challenge lies in dealing with collapsible competition ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...

When dynamically loaded HTML is involved, Javascript ajax calls often fail to execute properly

Currently, I am in the process of creating a JavaScript script that can facilitate clicking through <a href> links by only replacing the inner HTML instead of reloading the entire page. The interesting thing is, it seems to be functioning properly, e ...

Is it possible to obscure the PHP file path and conceal the parameters in a POST request?

Is there a way to securely increase the liking number on records in a database without exposing sensitive information through post requests? The PHP file and GET parameters are visible in the post request, allowing anyone viewing the page source to poten ...

The error message "Uncaught ReferenceError: require is not defined" is commonly encountered when using Webpack

Despite countless similar questions, none have provided a solution to my issue because the underlying problem seems to elude me. I am attempting to bundle files for the browser using webpack 4.26.1, but no matter what I try, I consistently encounter the er ...

What are some methods for utilizing the data received through this.props.history?

Whenever I need to navigate from one route to another using this.props.history.push("/"), I also want to pass along some extra data. For example: this.props.history.push('/postDetail', {data: item}). However, I am uncertain about where to define ...

Guidelines for managing UnprocessedItems with the AWS JavaScript SDK for dynamoDB

Currently, I'm facing an issue while attempting to utilize an AWS Lambda function for handling events from SendGrid. The event is expected to be in the form of an array containing a variable number of JSON objects, each representing a specific event. ...