blitzmann
blitzmann

Reputation: 7905

Number Formatting (input mask) in jQuery

I'm trying to format numbers in a text field like so:

123,456,789

I know that there are a lot of jQuery plugins to do this, however, they all change the actual value. I just want it to look formatted, and not be sent formatted.

For example, if I type in 23845 into my text field, I want it to visually convert to 23,845, but when I send the form I want it to send as 23845.

Does anyone know how I can achieve this? All other solutions I've seen change the actual submitted value.

Upvotes: 6

Views: 19658

Answers (2)

Atif Tariq
Atif Tariq

Reputation: 2772

Please try the following:

<script type="text/javascript">

        $(document).on('keyup', '.test', function() {
            var x = $(this).val();
            $(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
        });
    </script>

    <form>
       <input class="test" type="text" />
    </form>

Upvotes: 0

JMax
JMax

Reputation: 26591

AFAIK, the masks plugin do not change the value but only the display : http://plugins.jquery.com/plugin-tags/mask

[edit] within the list of all the plugins, i've used this one on my code : https://github.com/RobinHerbots/jquery.inputmask ([edit 2] and worked as you want i've checked the code where i used it and the default behavior is that it sends the mask with the value, you need to use an option to unmask as i've said in my comment)

Upvotes: 2

Related Questions