Upon clicking outside of the input field, ensure that there is a space added to the

I have these input boxes where integers are entered. My goal is to display them similar to the images below:

1:

https://i.sstatic.net/3HUbO.png

2:

https://i.sstatic.net/4722H.png

$(document).ready(function() {
  $("input").each(function() {
    $(this).blur(function() {
      var len = $(this).val().length;


    });
  });

});
 .ndInbox {
   background-color: white;
   width: 390px;
   height: 42px;
   box-shadow: 0 2px 2px 0 #C2C2C2;
   border: none;
   outline: none;
   font-size: 18px;
   margin-bottom: 10px;
   font-family: 'PT Sans', sans-serif;
   padding-left: 10px;
 }
 .ndLabel {
   color: #999;
   font-size: 17px;
   font-family: 'PT Sans', sans-serif;
 }
<table>
  <tr>
    <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avPurchase03">Average, &euro;:</td>
    <td colspan="2">
      <input id="lpcfIn02Id" class="ndInbox" type="text" value="" />
    </td>
  </tr>
  <tr>
    <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avNumber03">Budget, &euro;:</td>
    <td colspan="2">
      <input id="lpcfIn03Id" class="ndInbox" type="text" value="" />
    </td>
  </tr>
</table>

An incomplete jQuery implementation using blur was attempted but did not achieve the desired functionality. Can my requirements, as depicted in the pictures above, be realized?

Thanks in advance.

jsFiddle

UPDATE: By clicking outside the input box, I also mean moving to the next field when tabbing.

Answer №1

If you're looking to convert any input into a decimal with exactly two digits, you can achieve this by utilizing the Number() function for parsing and then formatting with toFixed():

<input class='make-decimal' />
<script>
    $(function(){
        // Trigger on blur
        $('.make-decimal').blur(function(){
            // Parse value as number and display as two digits
            $(this).val(Number($(this).val()).toFixed(2))
        })
    });
</script>

You can check out a demonstration here :

https://i.sstatic.net/8yc34.gif

To include spacing between digits, consider using Regular Expressions like below :

$(function(){
    $('.make-decimal').blur(function(){
        // Format number (without spaces)
        var formatted = Number($(this).val().replace(/\s/g,'')).toFixed(2);
        // Split decimal value
        var sections = formatted.split('.');
        // Insert space every third digit
        sections[0] = sections[0].replace(/\B(?=(\d{3})+\b)/g, " ");
        // Display updated content
        $(this).val(sections.join('.'));
    });
});

Find an example here :

https://i.sstatic.net/lhCg5.gif

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

Implementing the kendo-grid directive with a headerless row

Is it possible for the Kendo UI - Grid / AngularJS to display a grid without a header row? I am hoping to achieve this: https://i.sstatic.net/guYPf.jpg instead of this: https://i.sstatic.net/xlfgC.jpg If it is supported, what should the options in its ...

What is the reason behind the CSS not rendering when async:false is used?

I find it peculiar and am actively seeking an explanation for this anomaly. In my code snippet, the AJAX call seems to be causing unexpected behavior: $('.edit-config').click(function() { var that = this; var msg; ip ...

Trigger form submission with validation using jQuery

How can I redirect a user to another page named "free.php" from the index page without changing the URL, using jQuery? Below is an example I have created: http://jsfiddle.net/jKHQe/ The checkbox validation works in the example, but I am unable to redir ...

Show the date broken down into day, month, and year, as well as various combinations thereof

My goal is to display the current month, year, month-year, and day-month in my HTML page. Here is the JavaScript code I am using: var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", ...

Calculating the total value of individual sections using Jquery

I have multiple sections, each containing three input fields: <div class="product_quantity"> <div class="color-quantity"> <input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text"> ...

"Utilize jQuery to superimpose an image on top of

I'm attempting to create a feature where clicking on an image will reveal text underneath, similar to how retailmenot.com displays coupon codes. In addition, when the image is clicked, users should be directed to an external URL. Here is an example o ...

When attempting to download a PDF file through an API using JavaScript and React JS, it is found to be empty

After downloading a PDF file from the API, I encountered an issue where the PDF appears blank. Upon testing the API endpoint, I was able to view the byte stream on the console and save it as a File successfully. However, when receiving the same response in ...

Having trouble getting a background image to show up in a table cell when using CSS clear:both?

I am working on an email and I want an image to only show up on mobile devices. To achieve this, I created an empty <td> with a span inside where I styled the span to have a background image. However, my issue is that I want the image to occupy an e ...

Utilizing both animation and loading effects using jQuery

I'm attempting to slide out a div, then fade in content using a .load request once the animation is complete. I'm puzzled as to why this isn't working, but it seems to halt the animation and loading process entirely: $('.films'). ...

Unable to implement CSS styling on Bootstrap collapsible menu

When you visit this website and resize the browser window to reveal the toggle buttons, clicking on either one will only expand the dropdowns to a small portion of the screen width. I would like both dropdowns to stretch out and fill 100% of the available ...

Dealing with ETIMEDOUT error in Express.js

My Node.js/Express.js application interfaces with an FTP server, but crashes when the server is offline due to handling issues with the ETIMEDOUT exception. I am using the jsftp module for FTP. Here's the problematic part of my code: router.post("/" ...

Combatting repetitive code through the use of Redux toolkit and actions

My code is currently long and repetitive. I realize that using helper functions would help me cut it down and make it more maintainable and readable. As a React beginner, I have a question: Should I implement most of this logic with helper functions in a s ...

Tips for generating a JSON string with nested structure

Can someone assist me in generating a JSON based on the HTML elements provided below? { "AppName": "ERP", "ModuleDesc": [ { "Name": "Payroll", "AcCESSRIGHTS": [ { "Create": "Y", "Retrive": "Y", "U ...

Displaying the content of a modal window

I am working on a modal that needs to print only the content within it, nothing else. Here is the setup for the button inside the modal: This should not be printed... <button id="btnPrint">Print (this btn should not be printed!)</button> ...

Enhancing the Google canvas script to incorporate numerous markers

Currently, I am using a template that includes a Google map with coordinates set in JavaScript. The code for the marker on the map is as follows: //Google Map var latlng = new google.maps.LatLng(44.761128,21.227395); var settings = { ...

What is the method used by Chrome dev tools to create CSS selectors?

When setting a new style rule for an element, Chrome generates a selector that includes the entire hierarchy of elements instead of just the class name. For instance: <body> <div class="container"> <span class="helper"> ...

Tips for Loading an Alternate JavaScript File When the Controller Action Result is Null

My controller action is located in *controller/books_controller.rb* def search_book @found_book = Book.find_by_token(params[:token_no]) # After the book is found, I render the search_book.js.erb file using UJS respond_to do |form ...

"Troubangular: Troubleshooting unexpected behavior when trying to update ngFor after setting a property

Dealing with what seems like a straightforward component here. I'm fetching an array of objects from an API, storing them in a property, and then displaying them in a select list for the user to choose from. When the value changes, I filter the result ...

Tracking ajax calls with piwik: A step-by-step guide

I'm curious about how to enable piwik to track ajax requests. I know there is an API available, but I'm unsure about the exact steps I need to take in order to view ajax loaded pages in the dashboard. Could it be something like this: _paq.push( ...

Steps for redirecting to an external URL with response data following an HTTP POST request:

this.http.post<any>('https://api.mysite.com/sources', [..body], [...header]) .subscribe(async res => { const someData = res.data; const url = res.url; window.location.href = url }) After redirecting to the specified UR ...