Giter Club home page Giter Club logo

jquery-maskmoney's Introduction

jQuery maskMoney Build Status

Just a simple way to create masks to your currency form fields with jQuery.


Download

To get the latest(minified) version, click here.

You can also use CloudFlare's cdnjs. Just choose the version you want to use here.


Show Time!

To view a complete demonstration of it's features and usage, access our examples page!


Usage:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
  <script src="dist/jquery.maskMoney.min.js" type="text/javascript"></script>
</head>
<body>
  <input type="text" id="currency" />
</body>
<script>
  $(function() {
    $('#currency').maskMoney();
  })
</script>

Options:

The options that you can set are:

  • prefix: the prefix to be displayed before(aha!) the value entered by the user(example: "US$ 1234.23"). default: ''
  • suffix: the suffix to be displayed after the value entered by the user(example: "1234.23 €"). default: ''
  • affixesStay: set if the prefix and suffix will stay in the field's value after the user exits the field. default: true
  • thousands: the thousands separator. default: ','
  • decimal: the decimal separator. default: '.'
  • precision: how many decimal places are allowed. default: 2
  • allowZero: use this setting to prevent users from inputing zero. default: false
  • allowNegative: use this setting to prevent users from inputing negative values. default: false
  • formatOnBlur: delay formatting of text field until focus leaves the field. default: false
  • reverse: by default, maskMoney applies keystrokes from right to left. use this setting to apply keystrokes from left to right.
  • selectAllOnFocus: select all text in the input when the element fires the focus event. default :false
  • allowEmpty: allow empty input values, so that when you delete the number it doesn't reset to 0.00. default: false

IMPORTANT: if you try to bind maskMoney to a read only field, nothing will happen, since we ignore completely read only fields. So, if you have a read only field, try to bind maskMoney to it, it will not work. Even if you change the field removing the readonly property, you will need to re-bind maskMoney to make it work.


Bonus!

We have 3 bonus methods that can be useful to you:

  • .maskMoney('destroy') removes maskMoney from an element.
  • .maskMoney('mask') apply the mask to your input. This method can work as a setter as well, if you pass a value to it, like this .maskMoney('mask', 1999.99)
  • .maskMoney('unmasked') return a float value (ex.: 'R$ 1.234,56' => 1234.56). PS: If you have only one input field, you should use this way .maskMoney('unmasked')[0], since it will always return an array.

You can also configure maskMoney options using the data-* API instead of passing it as a hash in the .maskMoney method call. To use it, simply set the options using data-<option>, like this:

	<input type="text" data-affixes-stay="true" data-prefix="R$ " data-thousands="." data-decimal="," />

And when you bind maskMoney to that field, we will read those options. ATTENTION: for settings that isn't entirely lowercase, you will need to use dashes instead of capital letters. For example, to set allowZero, you will need to add a attribute called data-allow-zero.


Tests:

To run our test suite, just clone the repo and open test/index.html. If you want to run it using nodejs, clone the repo and run:

npm install
bower install
grunt test

Contributors:


License:

jQuery-maskMoney is released under the MIT license.

jquery-maskmoney's People

Contributors

abduncan avatar aureliosaraiva avatar bobeagan avatar danielrohers avatar elfalem avatar erikhenrique avatar fagnermartinsbrack avatar fjsj avatar gaetani avatar gmoore avatar julianealbuquerque avatar juniorgarcia avatar jzywien avatar kelvah avatar loureirorg avatar pbalduino avatar rogeriomorais avatar shaneog avatar victor-cruz avatar wbotelhos avatar yooontheearth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-maskmoney's Issues

create some tests

maybe use jasmine to create some tests for the plugin. we know that we need it :)

The mask doesn't take into account values with a decimal point

Firstly I'd like to say thanks for sharing this plugin its been a real help for my work.

The mask (with a precision of x) doesn't take into account the decimal point in the value passed to it.

e.g. with a precision of 2
Value 1.00 would be displayed as 0.01
Value 100.00 would be displayed as 1.00

Is there an option I'm missing or was the mask designed this way?

Kind Regards
Richard

maxlength check prevents input if (part of or all) current text (with already maxlength length) is selected

If a field is limited to e.g. 6 chars via maxlenth and a 6-figure entry is displayed, it is not possible to enter a new value if the complete (or partial) text is selected/highlighted in input field.

Testcase: jQuery( '.my-field' ).attr( 'maxlength', '6' ).maskMoney({ thousands: '.', decimal: ',', precision: 0, defaultZero: false, allowZero: false, allowNegative: false }).maskMoney('mask');

Enter 10000 in field, it becomes 10.000, mark/select complete text in field with mouse, try to type e.g. a number 2

Expected behaviour: The selected 10.000 disappears, new number 2 appears.

Actual behaviour: No number entry possible, in keypressEvent(e) the else if (input.val().length >= input.attr('maxlength')) is reached and false is returned.

Suggested addition: Check if complete or partial text is selected and allow overwrite of selected text until maxlength.

Thanks for this great plugin.

making this guy a better citizen

these methods need to become private and not extenal:
unmaskMoney
mask
setCursorPosition
getInputSelection

they will become this
.maskMoney('unmask')
.maskMoney('mask')
the other 2 methods will be vanished.

following this guidelines:
http://docs.jquery.com/Plugins/Authoring#Namespacing
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Plug_me:_Writing_your_own_plugins

this will make maskMoney a better citizen(mainly with @digitalBush's jquery.maskedinput)

start writing from the left

When I press the first key, this refers to the last decimal. I do not want to do that. I prefer this refers to the first number from the left. Is it possible?

Use defaultZero as default value

I have a bunch of forms where zero is ok as value to some fields, but they can't be blank, so we use "0,00" as default value.

The "defaultZero" option in maskmoney would force the user to (at least) enter the field and leave it, in order to fill the form appropriately. I can't see the benefit of this option as it is, so I'm here to ask how can I contribute with this feature.

If we use "defaultZero" as default value, could we be breaking some use case? Or should I create a "defaultValue" option and keep the existing one as it is?

Integrating with Ruby on Rails

Is there any trick to getting this to work with Ruby on Rails? I've been trying for a while and cannot seem to get it to work.

Usability poor due to 0 appearing onfocus

Love the plugin, however, I don't like that when an empty field takes focus, it immediately puts a 0 there. How can I get rid of this? I tried changing multiple lines but with no luck. Thanks for your help.

Keydown and Keyup Events fired repeatedly on Android 2.3

On Android 2.3, if you mask an input field with maskmoney the keydown and keyup handlers will be called over and over once the input field gains focus.
I have been unable to pinpoint thte cause.

To replicate:

  • Mask a field with maskmoney
  • Put breakpoints on the keydown/keyup events and/or breakpoints in the maskmoney keydown/keyup event handlers
  • Give focus to the input field
  • View the breakpoints being called over and over again

I did this on an HTC Thunderbolt and in the Android emulator

add an option to pass a numeric value to the "mask" method

As I told in #14 issue, I would like to return the numeric value of an input.
It would be nice, if I can set a numericValue into the input, by passing the number as a parameter to the mask method.
This is what happens today:

var abc = 1 + 1.5;
$('#var').val(abc);
$('#var').val() == 2.5

the idea is to do something like this:

$('#var').mask(abc);
$('#var').val() == "R$ 2,50";

BUG - Masked Input

Ainda, to tendo problemas com os seguintes plugins:

jQuery @Version: 1.7.2
MaskMoney @Version: 1.4.1
MaskedInput @Version: 1.3

Basicamente, se o MaskMoney , for incluido depois do MaskedInput, o MaskedInput não funciona.
Então para ter os dois funcionando, eu preciso chama-los assim:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="js/maskMoney.js"></script> <script src="js/jquery.maskedinput.js" type="text/javascript"></script>

O contrário não da certo.

Vi em uma postagem anterior que esse problema teria sido corrigido, mas eu ainda estou visualizando o BUG na minha aplicação.

some onchange events are "eaten"

What?
If you are editing an input value and click on the del button or the rub button, or even if you select another field with a left click , the currently edited field will not trigger any "change" event.

how?
if u call .maskMoney() on an obj, say: $("#myInput").maskMoney();
Then you will receive parcially the "change" event from that object ( for exemple: $('#myInput').bind('change',function() )

The fix:

around line 78, after:

else if (k==37||k==39) { // left arrow key or right arrow key
    return true;
}

add this condition to take care of the del and rub buttons, and make sure "change envent will be triggered":

else if (k==8||k==46) { //8: rub, del: 46
    clearDirt();
    $(this).change();
    return true;
}

Then look at the blur() method around 170 and add to the end of blur():

//loosed focus, bubble change event to other listeners if is dirty
if(dirty){
    clearDirt();
    $(this).change();
}

Thanks to fix this on trunk.

Removing mask to submit form

How can I do that?

I'm using this:

$('#field').maskMoney('destroy');

but this isn't working.

I'm trying avoid some error on my rails server like this

is not a number

Is there any simple way to do that?

Thanks in advance.

backspace error

If you try to backspace an already-entered value, an error occurs.

apostrophe (') is accepted

apostrophe ' and right arrow key are identical 39

else if (k==37||k==39) { // left arrow key or right arrow key
    return true;
} 

I deleted k==39 to make it work.

OS: Debian

Max value before decimal separator

Hi,

We have precision to set max precision after decimal separator, but i need a property to set max precision before decimal separator.

Example 1:

precisionBefore: 2
precision: 2

max result: 99.99

Example 2:

precisionBefore: 3
precision: 2

max result: 999.99

Force default value and maintain it when empty

I noticed that unless you call $('.selector').maskMoney('mask'); the field remains empty. it would be cool if this could be set by default as I would like to keep the empty values in the fields (0.00).
Note: This pull request solved this issue. (#34) It did require a minor change than what the pull request had but it's really simple to implement.

I also notice that onBlur, if the value is empty, it goes back to an empty field... So now I need to run

$('.selector').blur(function() {
        $(this).maskMoney('mask');
});

To fix the issue.
Note: allowZero:true fixed the blur issue

I need to do the same for focus as I do for blur since it seems to remove the default value when I focus the field.

$('.selector').focus(function() {
        $(this).maskMoney('mask');
});

Note: This pull request solved this issue. (#55)

If this was a setting it would be really cool. Only saves me a few lines of code but I think it's a very useful feature.

Thanks for this great plugin!

Mask only works after refresh.

So I am using the money mask in conjunction with jQuery mobile. The issue that I am having is that when you navigate to the page where the input box is, the mask doesn't work initially. If, however, you refresh the page, the mask works. Initially I thought this was an issue with needing to clear the cache, but the issue has persisted. Any idea what the issue might be here?

create a way to get the number from the input field

Sometimes I have to make some calculations with values that are formatted in the client side. It would be nice to have a method that transforms the input value into a number, like the following example:

var abc = 1 + 1;
$('#var').val(abc).mask();
$('#var').val() == '2'
$('#var').numericValue() == 2

Negative number pattern differ from jquery globalize pattern

Hello,

I'm using jquery globilize https://github.com/jquery/globalize and the maskMoney plugin.
The problem is that the maskMoney use a fixed format like: $-10.0. and actual culture thah I'm using in globilize (https://github.com/jquery/globalize/blob/master/lib/cultures/globalize.culture.pt-BR.js) use the format -$10.00.

I think I don't prefer the format used in the maskMoney. Is there any kind of customization to change its format pattern?

Triggering maskValue()

I like jquery-maskmoney but find that I need to apply formatting to calculated, read-only fields. I've added the following code to the plugin, which allows me to trigger a 'mask' event on an input field whenever I want. Any chance of adding to the next release?

Thanks, Steve

        function mask() {
            var value = input.val();
            input.val(maskValue(value));
        }
        input.bind("mask", mask); 

backspace error

Hello,

I execute the code, but find the error on backspace.

"maskAsDirty is not defined" line error 124

Help me

Thank you

Original value is changed when precision does not match precision of original value

When applying maskMoney to a field I see that it changes the value of my input. For example, if my input is set to 1000.500 and I apply the following options:

            $('.mask-money').maskMoney({
                symbol: '$',
                precision: 2,
                showSymbol: true,
                allowZero: false,
                defaultZero: false,
                symbolStay: true
            }).maskMoney('mask');

Then it will change my field to show 10005.00. I would like to add a new option called keepOriginalValue or some such option. What do you think?

number overflow problem

currently, the implementation of maskValue function uses parseFloat to format the string. this cause a problem with really big numbers, making the input field to be reseted. following a log that logs the values of a and n in the line var n = parseFloat(a);:

111111111111 jquery.maskMoney.js:229
111111111111 jquery.maskMoney.js:231
------------ jquery.maskMoney.js:228
1111111111111 jquery.maskMoney.js:229
1111111111111 jquery.maskMoney.js:231
------------ jquery.maskMoney.js:228
11111111111111 jquery.maskMoney.js:229
11111111111111 jquery.maskMoney.js:231
------------ jquery.maskMoney.js:228
111111111111111 jquery.maskMoney.js:229
111111111111111 jquery.maskMoney.js:231
------------ jquery.maskMoney.js:228
1111111111111111 jquery.maskMoney.js:229
1111111111111111 jquery.maskMoney.js:231
------------ jquery.maskMoney.js:228
11111111111111111 jquery.maskMoney.js:229
11111111111111112 jquery.maskMoney.js:231
------------ jquery.maskMoney.js:228
111111111111111131 jquery.maskMoney.js:229
111111111111111140 jquery.maskMoney.js:231
------------ jquery.maskMoney.js:228
1111111111111111381 jquery.maskMoney.js:229
1111111111111111400 jquery.maskMoney.js:231
------------ 

we need to handle this by just doing replaces using strings, instead of using real numbers.

Entering negative number with showSymbol produces duplicate negative sign

Entering negative sign prior to typing in a number when using showSymbol causes negative sign to appear after dollar sign instead of before. Also occurs with various combinations of entering number/negative sign and entering and leaving field.

Example output produced: -$-433.43 and $-$665.55

Data Dash API

I really needed this plugin to have a data- API, so I extended it a little. If you find this valuable, please add it or lemme know if I can submit a pull request.

http://jsfiddle.net/bt7tV/

Conflito com jquery.ui.mask.js

Está td perfeito, mas uso a jquery.ui.mask.js para CEPs, FONEs etc. Quando 'carrego' a maskMoney, está desabilitando a jquery.ui.mask.js

sucesso!

Problema usando IE 9

Achei um problema muito engraçado testando seu script no IE 9. Via http://plentz.org/maskmoney/ acontece o seguinte erro que segue abaixo:

SEC7112: O script de https://raw.github.com/plentz/jquery-maskmoney/master/jquery.maskMoney.js foi bloqueado devido a um tipo mime incompatível
maskmoney.htm
SCRIPT438: O objeto não oferece suporte à propriedade ou método 'maskMoney'
maskmoney.htm, linha 17 Caractere 1
SCRIPT438: O objeto não oferece suporte à propriedade ou método 'maskMoney'
maskmoney.htm, linha 21 Caractere 1
SCRIPT438: O objeto não oferece suporte à propriedade ou método 'maskMoney'
maskmoney.htm, linha 25 Caractere 1
SCRIPT438: O objeto não oferece suporte à propriedade ou método 'maskMoney'
maskmoney.htm, linha 29 Caractere 1
SCRIPT438: O objeto não oferece suporte à propriedade ou método 'maskMoney'
maskmoney.htm, linha 33 Caractere 1
SCRIPT438: O objeto não oferece suporte à propriedade ou método 'maskMoney'
maskmoney.htm, linha 38 Caractere 1

Ai resolvi baixar o script na minha máquina chamando o script local e nao mais pelo endereço: https://github.com/plentz/jquery-maskmoney/raw/master/jquery.maskMoney.js ... ai tudo funciona normalmente. Talvez seja por conta do https, mas fica a dica.

Abraço.

ReferenceError: blurEvent is not defined [Firefox]

Having this issue right in line 24:

else if ($.browser.mozilla) {
this.removeEventListener('input', blurEvent, false);
}

if I comment this line, it works. Didn't understand the reason of this line, can anyone help me?

Thanks.

Data entry on MVC3 site using Firefox 16.0.2 version

Assgining the maskMoney using an Editor template (code below is in editor template) I am unable to enter any numbers. It is possible to use the backspace or delete keys to clear out existing number when the control is filled when current data but no new data can be entered. Also, when creating new entry the control will not accept numbers at that time either.

@using System.Web.Mvc.Html;
@using Resources;

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" })
<script type="text/javascript">
    $(document).ready(function () {
        $('#@ViewData.ModelMetadata.PropertyName').maskMoney();
    });
</script>

maskmoney on Chrome doesn't insert typed numbers correctly

I am using the maskmoney JS plugin and Chrome web browser 18.0.1025.168 m
maskmoney @Version: 1.4.1 @Release: 2011-11-01

When I type into an input field with no maxlength set it seems to try and insert the numbers from right to left, starting with the cursor between the initial $ and 0 chars. So typing 4000 till insert the 4 to the left of the 0 (showing $|40 where | is the cursor position.) It stops accepting input at this point. I have to click to the right of the 0 and type the remaining 00.

If I click into the input field and type 650, I get $5060 which is whacky.

I have a screencast movie of the above example viewable here: http://screencast.com/t/Oukpjxytf4

Here is the input tag I'm using here:

The JS for formatting field is:

// format the currency figures
$(".textbox-number").maskMoney(
{
    allowZero:true, 
    symbol:'$', 
    showSymbol:true, 
    precision: 0, 
    defaultZero:true, 
    allowNegative:true
}); 

Why is it behaving this way in Chrome?
In Firefox 12 it works fine.
In IE 9 it works fine

Getting a warning in chrome

event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed from the engine in the near future

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.