Search code examples
jqueryjquery-ui-spinnerjquery-globalization

JqueryUI spinner numberformat currency submit number value


I have a jquery currency input and I am using this code:

$('input[name="precio"]').spinner({
    min:0,
    numberFormat: 'C'
});

The input works perfectly as it shows the number as a number with the $ or € sign depending on globalize.

The problem is that when I submit the form I get the text like this "5,00 €" and I would like it to be 5.00 or 500, just the number value.

Is there any way to do this? Thanks in advance.


Solution

  • Ok I finnaly managed to do this the way I wanted. I've just created a plugin named currencyspinner that extends spinner from JQueryUI, here is the code:

    $.widget( "ui.currencyspinner", $.ui.spinner, {
         options: {
            numberFormat: 'C',  // Currency Format
            min:0,
            step:0.10
        },
        _create: function(){
            this.hidden = $('<input type="hidden" value="'+this.element.val()+'" name="'+this.element.attr('name')+'">');   // Create a hidden input with the same name and value
            this.element.removeAttr('name');    // remove the name of the original element
            this.element.before(this.hidden);   // insert the hidden element before the original element
            return this._super();
        },
    
        _refresh: function() {
            this.hidden.val(this._parse(this.element.val()));   // put the aria-valuenow on the original element
            return this._super();
        },
    
        _destroy: function(){
            this.element.attr('name',this.hidden.attr('name')); // put back the name on the original value
            this.hidden.remove();                               // remove the hidden element
            return this._super();
        }
    });
    

    I create a hidden input with the same name and give it the value of aria-valuenow each time the spinner refreshes.

    BE CAREFUL if you are trying to acess the currencyspinner after creating the currencyspinner you cannot use $('input[name="nameoftheelement"]').currencyspinner(...); as this will be the hidden input and not the spinner itself.

    I Hope it helps someone!