Search code examples
javascriptformattingform-submitnouislider

Submit initial value when using Javascript number formatting


I'm using number formatting (wNumb) for a text field. It gets updated by the range slider (noUislider) and that works fine.

The issue I'm experiencing is that when I submit the form, the saved value is divided by 1000 (probably due to the thousands separator).

How could I get rid of wNumb formatting when submitting?

...
<%= f.text_field :salary, id: "how-much" %>

 <div id="slider-format"></div>

  <div class="field">
    <%= f.label :comment %><br>
    <%= f.text_area :comment %>
  </div>
  <div class="actions">
   <%= f.submit %>
 </div>

Then the script below :

<script>
var sliderFormat = document.getElementById('slider-format');

noUiSlider.create(sliderFormat, {
    start: [ 200000 ],
    step: 1000,
  connect: 'upper',
    range: {
        'min': [ 10000 ],
        'max': [ 250000 ],
    },
  format: wNumb({
        decimals: 0,
        thousand: '.',
        postfix: ' (US $)',
    })
});

var inputValue = document.getElementById('how-much');

sliderFormat.noUiSlider.on('update', function( values, handle ) {
    inputValue.value = values[handle];
});

inputValue.addEventListener('change', function(){
    sliderFormat.noUiSlider.set(this.value);
});
</script>

The instructions on http://refreshless.com/wnumb/ are the following... I don't understand how to use that if this is what I should use.

Usage
var moneyFormat = wNumb({
    mark: '.',
    thousand: ',',
    prefix: '$ ',
    postfix: ' p.p.'
});

// Format a number:
moneyFormat.to( 301980.62 );
=> '$ 301,980.62 p.p.'

// Get a number back:
moneyFormat.from( '$ 301,980.62 p.p.' );
    => 301980.62

Solution

  • While saving value to input you need to add numbers only to some attribute of input tag.

    sliderFormat.noUiSlider.on('update', function( values, handle ) {
      inputValue.value = values[handle];
      $(inputValue).attr("actual", parseFloat(values[handle]).toString().replace('.',''));
    });
    

    And then you can replace value with attr actual while submitting form.

    $("form").on("submit",function() {
      $("#how-much").val($("#how-much").attr("actual"));
    });
    

    I hope this works as per your requirements.