JavaScript: The function is encountering issues with properly formatting the numbers

I am currently facing an issue with a function I have created to format numbers for currency by inserting commas every 4 digits. The problem lies in the fact that the first 4 numbers do not have a comma added where it should be, and the formatting only works when a space is entered. Furthermore, I am puzzled as to why my input field allows the spacebar to be entered even though I have restricted it. Any insights on these issues would be greatly appreciated. Thank you!

   <script>
    // Function to process key press events
      function keypress(e){
                var z="";
                var minStr = document.getElementById('min').value;
                var charval = String.fromCharCode(e.keyCode);
                var backspaceKey = String.fromCharCode(8);
                var tabKey = String.fromCharCode(9);
                var enterKey = String.fromCharCode(13);
                var spaceBarKey = String.fromCharCode(32);
    // Validation to only allow certain key entries
                if(         isNaN(charval) &&
                            charval != backspaceKey &&
                            charval != tabKey &&
                            charval != enterKey &&
                            charval == spaceBarKey){
                    return false;
                }
                // Adding commas every 4 digits
                if(minStr.length > 1 
                  && charval != backspaceKey
                  && charval != tabKey
                  && charval != enterKey
                  ){

// Adding commas to the string
                    minStr = minStr.replace(/\D/g, "");
                    var minArray = minStr.split("");
                    var j = 0;
                    for(var i = minStr.length; i > 0; i--){
                        if(j == 3){
                            minArray.splice(i, 0, ",");
                            j = 0;
                        }
                        j++;
                    }
                    minArray = minArray.join("");
                    document.getElementById('min').value = minArray;
// Adding a comma to the first 4 digits
                    if(minStr.length == 4){
                        var minArray = minStr.split("");
                        minArray.splice(1, 0, ",");
                        minArray = minArray.join("");
                        document.getElementById('min').value = minArray;
                    }
                }   
            }
    </script>
    <body>

      <input type="text" name="min" id="min" class="mini" onkeydown="return keypress(event)" placeholder="Enter the Min">
      <input type="text" name="max" id="max" onkeydown="return keypress(event)" placeholder="Enter the Max">

    </body>

DEMO: https://jsfiddle.net/efoc/dtqfLp05/

Answer №1

Your code has been successfully updated-

keydown--> keyup

String.fromCharCode(e.keyCode)--> e.keyCode(used direct keycode)

Take a look at the changes made here- https://jsfiddle.net/dtqfLp05/1/

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

Setting the title attribute for option elements in a select element that is bound to a model using AngularJs

I'm currently working on an HTML select element that is connected to an ng-model. Here's what the setup looks like: <select data-ng-model="accountType" data-ng-options="at.name for at in accountTypes"></select> This is how my accou ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

Setting a header with the Axios module and Vue.js in Nuxt: A step-by-step guide

I've been attempting to set up an "Accept-Language" header for my SPA using vue.js (along with nuxt). Here's the approach I took, but unfortunately, it's not functioning properly. I specified that I am utilizing the axios module for nuxt. ...

Wait until the link is clicked before showing the list element

Is there a way to prevent the display of list element id="two" in the code below until link "#two" has been clicked, removing element id="one"? I am looking for a CSS or JS solution that completely hides the list element rather than just hiding it from vie ...

Ways to activate jQuery validation when submitting a form instead of triggering it on blur

I am currently utilizing the Jquery Validation plugin to validate form fields upon submission. However, I have encountered an issue where incorrect email format triggers a validation message when moving to the next input field. This behavior is undesirable ...

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

Ajax request unable to load Image Slider

I'm currently implementing an Image Slider from this source For the site structure, I've set up an index.html file to display all the pages, allowing navigation by changing the content within <div id="isi">. Here's a snippet of the in ...

Insert a design layout into a text entry box

Currently developing an application with AngularJS and seeking a solution for adding a "template" to an HTML input field similar to a placeholder. Specifically, I have a date-field requiring user input in the format of dd/MM/yyyy or through a datepicker se ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

The method for retrieving and entering a user's phone number into a text field upon their visit

Objective: To enhance the user experience by automatically filling in the phone number input field when a mobile user views the page, making it easier to convert them into leads. A privacy policy will, of course, be in place. This page will offer a promo ...

Is it possible to utilize xmlhttprequest.open and xmlhttprequest.send to create a new browser window?

I am in need of a pop-up editor that allows users to choose what to edit, with the ID being sent to a new window. In this new window, data will be retrieved from a database, displayed for editing, and changes can be saved. Once the edits are completed, the ...

Material UI - sending an icon as a property

I need help with inserting a material-ui icon into my component using props. Can you please advise on what I might be doing wrong? I am struggling with passing the icon down in JSX, and here is the attempt that is not working: This code snippet shows me t ...

What are the steps to troubleshoot a Node Package Manager library in Visual Studio Code?

I have created a Typescript library that I plan to use in various NodeJS projects. The source code is included in the NPM package, so when I install it in my projects, the source also gets added to the node_modules folder. Now, during debugging, I want to ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Learn how to automatically retrieve messages without refreshing the page by leveraging the power of AJAX

displaying notifications with:- $call = "SELECT * FROM `chat` WHERE fromthe = '$email' and tothe='theadmin' UNION ALL SELECT * FROM `chat` WHERE fromthe = 'theadmin' and tothe='$email' order by id desc"; mysqli_quer ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Connecting a button's action to a specific element in an array using AJAX and Firebase

I am currently working on a project that involves making an AJAX request from a social API and then appending the results with a button inside the div. This button is meant to save the corresponding item in the array to my Firebase database. For brevity, ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...