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

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

How can I prevent the interpolation of "${variable}" in HTML when using AngularJS?

I need to display the string ${date} in a div element: <div>please substitute the ${date} as the tag for the name</div> The displayed content should be: please use the ${date} as the substitute tag to the name. However, the browser interpre ...

php Use cURL and the DOM to extract content with specified CSS styling

Unclear in the title, I want to copy all content from a specific div on an existing webpage (not owned by me). The code successfully extracts the content. Extractor code: // Get Data $curl_handle=curl_init(); curl_setopt($c ...

Tips on hovering over information retrieved from JSON data

Within my code, I am extracting information from a JSON file and placing it inside a div: document.getElementById('display_area').innerHTML += "<p>" + jsonData[obj]["name"] + "</p>"; I would like the abi ...

Filter the array and determine the number of elements in the filtered array

I am looking to filter the contents of two arrays and then count the elements where "isimplemented: 'Yes'" is true: const array1 = [{ProjectName: "IT", Department: "Software"}] const array2 = [{Name: "IT", isimplemented: "Yes"}] The method I at ...

Show the nested div when hovering over the containing div using JavaScript

I have a situation where I have multiple divs within a parent div, all using the same class. Here is an example: <div class="deck-content"> <div class="deck-box">TEST< <div class="deck-hidden">< <span class= ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...

Determine the selected radio button

----EDIT---- I am developing a jQuery mobile application and I need to determine which radio button is selected. This is the JavaScript code I'm using: function filter(){ if(document.getElementById('segment1').checked) { aler ...

Executing a function in jQuery by including a variable

I am trying to make an Ajax call to the server using jQuery's .get method. Here is the code I am using: $.get("InfoRetrieve", { },addContent(data)); The goal is to retrieve data from the server and pass it to a function called addContent. This is ...

Ways to retrieve Payload following the Request url access

Currently utilizing Selenium with Python to conduct website testing, I successfully accessed the Request link and now aim to access the Payload. Below is an image displaying the process: view image description here driver = webdriver.Chrome(options=option) ...

Phonegap experiencing issues with executing JavaScript code

My attempt to utilize phonegap is encountering an issue where my javascript is not running. Here's what I've tried so far: <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" / ...

Top method for implementing select all checkboxes in a table

Hey there! I'm new to VueJS and I've been working on creating a data table component. So far, I have built two components called ui-datatable and ui-checkbox, which allow me to select all rows in the table. It's functioning perfectly fine, b ...

Which specific element should the userEvent.type(...) function target in order to work effectively with MUI's DesktopDatePicker TextField component?

Is there a way for me to input text into the TextField input within the MUI datepicker using react-testing-library's user-event? I've noticed that there is a mask applied to the input. I attempted to use userEvent.type(inputEl, '1') an ...

Whoops! Unable to interpret properties from an undefined source while trying to retrieve 'get'

Every time I execute my program, I encounter the following error: Cannot read properties of undefined (reading 'get') TypeError: Cannot read properties of undefined (reading 'get') at Proxy.mounted (webpack-internal:///./node_module ...

ConnectionError: 404 Page Not Located

Why am I receiving downvotes? This is the second time I've been downvoted. Please, at least tell me the reason so that I can improve. I am currently using the jQuery get method to send data from HTML to PHP (both are hosted on localhost/Site1). Edit ...

Determine the exposed area of an element with overflowing content

I am looking for a way to determine which text within an element (such as a div or textbox) is currently visible when there is overflow. As the user scrolls, I need to have an updated list of the visible text. I am open to using any elements, but only a ...

Learn how to dynamically apply a CSS attribute for a set period of time using jQuery and automatically revert it back to its original state after 2 seconds

Is there a way to apply a CSS attribute to a specific element (like a div) for only 2 seconds? Here is what I have tried so far: HTML: <div class="custom-div">bar</div> <input class="button" type="button" value="press me" /> JQuery: $ ...

What is the best way to locate an element with the class name being an email address using jQuery?

Is it possible to locate an element with an email address as the class name, considering that the email address varies? $(document).ready(function(){ //not working getting error var email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

A step-by-step guide on creating a unique ticket number sequence in PHP

Looking to create a unique ticket number sequence using PHP? Here's the given sequence: 1-W1 (mandatory). 2-Date (yy-dd-mm) format. 3-001-999 (resets daily from 001). Check out this example: e.g. - W120200101001 I've started the code below, b ...