-2

I have this code:

<input class="form-control only_number" id="milesamount_1" name="AboutYouDetail[miles_amount][1]" type="text">

$('.only_number').on('keypress keyup select change', function (evt) {
            var nmbr = $(this).attr('id').split('_')
            var milesamount = $('#milesamount_' + nmbr[1]).val()    
            var new_milesamount = String(milesamount).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        $('#milesamount_' + nmbr[1]).val(new_milesamount)
            console.log(new_milesamount);
    })

In the console the number is showing correctly say, if I input 123454342 it shows as 123,454,342 but in the input field it shows as 1,2,3,4,5,4,342

How do I fix this to show the , only after every 3 digits?

LTech
  • 1,677
  • 5
  • 29
  • 48
  • When you are viewing this in the console, aren't you checking the errors and fixing them? – prettyInPink Aug 24 '23 at 09:19
  • there are no errors showing in the console. I just see: 1 12 123 1,234 12,345 123,454 1,234,543 12,345,434 123,454,341 – LTech Aug 24 '23 at 09:34
  • Never modify the input value as the user types. Use instead the `"blur"` event (when the user focuses out of the input). – Roko C. Buljan Aug 24 '23 at 09:47
  • https://jsfiddle.net/fuacb4xy/ – Alive to die - Anant Aug 24 '23 at 09:48
  • Also, why `"keypress keyup select change"`? Use only the `"input"` event if you're not interested in the pressed key. – Roko C. Buljan Aug 24 '23 at 09:50
  • I think the problem is as you say, keypress etc can you please show me how to adjust the code using blur or input. I can't figure it out. – LTech Aug 24 '23 at 09:57
  • the code seems to work after a delay of a second or so. but then the number jump back eg if I input 198232 it shows 198,232 after a second but then it jumps to just 198 if I fill in other fields on the form. I need it to be instant as they type – LTech Aug 24 '23 at 10:26
  • @LTech for that use another area to show comma-separated numbers. don't paste it to the input field itself. because once a comma-separated value is entered into the input you have to remove it fully and then start typing again for the next value – Alive to die - Anant Aug 24 '23 at 10:42
  • is there a way to change it while I'm typing? The issue is I'm using this field to calculate a total field which needs to be updated as I type. It has now stopped working. I have this code that follow - $('.only_number').on('keypress keyup select change', function (evt) { //calculate total price before key event – LTech Aug 24 '23 at 11:04

0 Answers0