Is there a way to insert a dot after every two digits in a text field using Javascript upon keypress?

When inputting a 4-digit number (e.g. 1234) in my text field with value format 00.00, I want it to automatically adjust to the 12.34 format. How can I achieve this behavior using JavaScript on keyup event?

Answer №1

Check out this code snippet:

    <script>
function roundNumber(myString){
//alert(mystring);
myString=myString.replace(/\./g,'');
myString = myString.substring(0, 4);

var myString1 = myString.substring(0, 2);
var myString2 = myString.substring(2, 4);

myString2=""+myString1+"."+myString2+"";
//alert(myString2);
if(myString!="" && myString.length > 2){
document.getElementById("round_no").value=myString2;
}

}



</script>

<input type="text" id="round_no" value="" maxlength="5" onkeyup="roundNumber(this.value)">

Answer №2

Consider Using Regular Expressions:

$(function() {
  $('input[type=text].two').on('input propertychange', function(e) {
    this.value = this.value.replace(/\D/g, '').replace(/(\d{2})(\d*)/, '$1.$2');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" autofocus='' class='two' />
<input type="text" class='two' />

Using .replace(/\D/g, '') will only leave digits in the value and

.replace(/(\d{2})(\d*)/, '$1.$2')
will split the value with a dot separator.

Answer №3

It doesn't function that way. When the format is 00.00, it will result in 1234.00

Answer №4

this issue has been addressed previously in a different discussion: How to format numbers with commas as thousands separators in JavaScript

// currently based on the solution provided in the above reference: replace (\d{3}) with 2,

however, it would be beneficial to understand the specific objective behind this formatting requirement, in order to provide a comprehensive and accurate response. For more insights, please refer to the link shared above.

<---

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

Creating a dynamic hover drop-down navigation bar in ASP.NET

After successfully creating a navigation bar with hover effects, I am now looking to implement a dropdown list when hovering over the items. Can anyone provide guidance on how to achieve this? Below is the current code snippet I am working with: <ul c ...

Do the Push Notification APIs in Chrome and Firefox OS follow the same set of guidelines and standards?

Do Chrome and Firefox OS both use Push Notifications APIs that adhere to the same standard? If not, is either one moving towards standardization? ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

I have noticed that the brand section of the navigation bar changes to black when I hover over it, but I have been unable to locate any

I'm currently working on a Rails application that has a navbar-top with a brand element. However, I've encountered an issue where the background of the brand element turns black when I hover over it. Despite inspecting the browser console, I coul ...

An issue has been encountered in the code during the installation of react.js

node:internal/modules/cjs/loader:1148 throw err; ^ Error: Module 'C:\Users\hp\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js' could not be found. at Module._resolveFilename (node:internal ...

Is there a way to alter the background image of the logo specifically for mobile device viewing?

Here is a snippet of my HTML code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="{{ route('home') }}"> <img src="{{ asset('assets/images/logo-school-icon.png') }}" ...

Explain the mechanics of the calculator code operating by inputting numerical values in a string format

Recently, I attempted to create a calculator in JavaScript and encountered a requirement to place the button values within single quotes as if they were strings. It's fascinating how these string values can work alongside operators to produce the desi ...

Issues with AJAX causing MYSQL to get NULL data inserted

My HTML code collects latitude and longitude coordinates and sends them to a PHP script using AJAX. However, the issue is that the AJAX request inserts NULL values into the database table. It seems to be inserting "0.000000" for both Latitude and Longitude ...

Combining a name using JavaScript even if certain parts are not available

How can I efficiently combine name elements without any extra white space in Vue.js? let FirstName = "John" let MI = "G" let LastName = "Jones" let Suffix = "Jr." I want to create let fullName = "John G Jones Jr." However, in cases like this: let First ...

Label text facing positioning difficulties

Hey there! I have a goal in mind: https://i.stack.imgur.com/bnso9.png This is what I currently have: http://codepen.io/KieranRigby/pen/QyWZxV. Make sure to view it in "Full page" mode. label { color: #6d6e70; bottom: 0; } .img-row img { width: 10 ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

What is causing the error message stating that the DateTime class object cannot be converted to a string?

I found this code snippet on a programming forum function increaseDate($date_str, ${ $date = new DateTime($date_str); $start_day = $date->format('j'); $date->modify("+{$months} month"); $end_day = $date->format(&apo ...

Showing different HTML elements based on the link that is clicked

Recently, I delved into the world of web development and decided to test my skills by creating a basic webpage with an interactive top navigation bar. Depending on the link clicked, specific HTML elements would be displayed while turning off others using a ...

Using Three.js to transfer one object's rotation to another object

I have been attempting to transfer one object's rotation to another with no success using the following methods: //The first method rotates much faster than the original object's rotation boxme1.rotateOnAxis(new t.Vector3(0,1,0), cube.rotation.y ...

Can you explain the distinction between using "require" to return a module and accessing the actual object in node.js?

When working with node.js, the commonly used method to include modules from other files is by using "require", whether it's from our own code or third-party libraries. But for me, there seems to be some confusion regarding the distinction between the ...

increasing sticky header, refreshes the scroll location of the website

My website has a fixed header that expands to reveal more content when a button is clicked. However, I noticed that if the page has been scrolled down before clicking the button, the scroll position resets to the top of the page. To see this issue in acti ...

Emphasizing the content of the text file with the inclusion of span tags

I am relatively new to working with angular js and javascript. I have a document or text file that looks something like this: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dumm ...

Switching Font Family Option for Selection Mat in Angular Material

I'm currently working on changing the font of the options inside mat-select ("In what city were you born", etc). After some experimentation, I found that by setting ViewEncapsulation to none (allowing styles from other files to bleed in), I am able t ...

Enzyme fails to locate text within a div even though it is present

In my current test scenario, I have a set of data displayed in Material-UI Cards. The data is provided through a JSON array consisting of objects with fields like projectName, crc, dateCreated, createdBy, and lastModified. { projectName: 'P ...

Label for the checkbox is covering other content on the screen in 1024 x 768

Here is the JSP code snippet: <h:field path="configuredChannels" required="true" code="admin.menu.channels"> <div class="row-fluid" data-channel-checkboxes="#"> <form:checkboxes element="div class=&apos ...