Anona
Anona

Reputation: 253

How can I make this number input accept commas?

I have a input in a website, the type of this input is number. Because of this I can't enter a comma which is needed.

Can some one teach me how I can make my input number and comma only?

This is the input I have ATM:

Bedrag: <input type="number" step="any" min="0" name="goed_doel_bedrag" id="goed_doel_bedrag" placeholder="Vul hier het bedrag in">

This needs to be a decimal point comma (not thousand).

Upvotes: 1

Views: 4902

Answers (2)

Mr.Web
Mr.Web

Reputation: 7176

Ok, in this type of job you should use JS and/or jQuery.

First create a function:

function commaOnly(input){ 

    var value = input.val();
    var values = value.split("");
    var update = "";
    var transition = "";

    var expression=/(^\d+$)|(^\d+\.\d+$)|[,\.]/;
    var finalExpression=/^([1-9][0-9]*[,\.]?\d{0,3})$/;

    for(id in values){           
        if (expression.test(values[id])==true && values[id]!=''){
            transition+=''+values[id].replace('.',',');
            if(finalExpression.test(transition) == true){
                update+=''+values[id].replace('.',',');
            }
        }
    }
    input.val(update);
}

This will turn dots into commas and accepts only one comma. This way if someone presses the dot, that's going to be changed to a comma instead of blocking his input.

Then assign that function to your input:

$('#goed_doel_bedrag').keyup(function (e) {
  commaOnly($(this));
});

And change to input type text:

<input type="text" step="any" min="0" name="goed_doel_bedrag" id="goed_doel_bedrag" placeholder="Vul hier het bedrag in">

Fiddle here: jSFiddle

Upvotes: 2

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201896

An input element with type=number accepts commas if the user interface provided by the implementation is written or configured to accept localized input that uses commas in numbers. This is determined by browser and/or system settings, and you cannot set in your code.

The conclusion is that such elements are useful only when you are willing to accept the variation in user interfaces. Each user can input numbers in a manner dictated by his browsing environment, and the browser is expected to canonicalize it to a specific internal format (e.g. converting 5,63 to 5.63 if the locale uses the comma as decimal separator).

If you don’t want that, you need to use other methods, such as type=text.

Upvotes: 4

Related Questions