Search code examples
javascriptjquerytwitter-bootstrap-3nouislider

Perform a simple multiplication with jquery after a slider value is set


I need some advice (help) on the most efficient way to implement a form that incorporates a range slider to set a value (in this case annual mileage), then takes that value and multiplies it by a set constant (0.05) and plugs the result into a second form field with a unit of British Pounds (£) and an accuracy of 2 decimal places rounded as appropriate. I am using a slider called No UI Slider (http://refreshless.com/nouislider/) and have set up the basic elements here:

$("#sliderAnnualMileage").noUiSlider({
start: [ 0 ],
step: 1000,
range: {
'min': [ 0 ],
'max': [ 120000 ]
 },
connect: "lower",
serialization: {

lower: [

  $.Link({
    target: $("#mileage"),
    format: {
      thousand: ',',
      decimals: 0,
      postfix: ' miles'
     }
    })
  ]
 }
});

Here is a partially working JS Fiddle: http://jsfiddle.net/highlander/jMA98/1/ Any insight or experience you have would be much appreciated.


Solution

  • You can set another $.Link to the second input box, with a formatting function:

    lower: [
      // your one
      // then this:
      $.Link({
        target: $("#annualSavings"),
        method: function (val) {
            $(this).val("£" + (val * 0.05).toFixed(2));
        }
      })
    ]
    

    This is the result: http://jsfiddle.net/jMA98/3/