Jochem Kuijpers Jochem Kuijpers - 5 months ago 72x
Javascript Question

Currency input with Twitter Bootstrap (using jQuery)

I'm using Twitter Bootstrap (v3) and I want to make a money input, where I can enter an amount of money with a fixed currency (currently €).

The input type needs to be

because of how I want the input to look on mobile devices (not a big QWERTY keyboard, just numbers), but I do want to allow multiple patterns.

I think the way to go is with the .on("input", callback) method, but I'm not sure how to accomplish this.

I have tried the following:

$(document).ready(function() {
$("#amount").on("input", function() {
// allow numbers, a comma or a dot
$(this).val($(this).val().replace(/[^0-9,\.]+/, ''));

(for the HTML and CSS, see the jsfiddle link)

But obviously that doesn't work, otherwise I wouldn't be posting here. Whenever you try to type something invalid, the whole string disappears.

Explanation rather than (or alongside) a working example highly is appreciated.


It is the type of input field 'number' that comes in the way. It has its own keyup/input handler attached (modern browsers deal with it via JS code too) and seems to break things.

If you use <input type="text" required="" placeholder="42,00" class="form-control" id="amount" /> then this works:

$(document).ready(function() {
    $("#amount").on("input", function() {
        // allow numbers, a comma or a dot
        var v= $(this).val(), vc = v.replace(/[^0-9,\.]/, '');
        if (v !== vc)        

The only drawback of this approach is that if you try to put bad character in the middle of the string, cursor jumps to the end. And, of course, you can type multiple dots and commas.

Better approach would be to keep last good value stored in data and test the whole string and replace if new character invalidates match for the whole string.


When input type="number" value contains non-number, jQuery val() returns empty string. This is why your code is not working. If "number" is a must (e.g. for numeric mobile keyboard), an approach would be to keep last known correct val() and put it back into control.