开发者

Add thousand separators to output from jQuery Slider plugin

I'm using the jQuery Slider plugin (jqueryui.com/demos/slider/)

I'm calling the plugin with the following Javascript:

$(function(){
 $("#slider-price").slider({
 range: true,
 min: 0,
 max: 5000000,
 step: 100000,
 values: [0, 5000000],
 slide: function(event, ui) {       
 $("#amount").val('£' + ui.values[0] + ' - £' + ui.values[1]);
}
});
});

And printing onto the page with the mark-up:

<label for="amount">Price : </label>
<input class="bar-price" type="text" id="amount" />
<div id="slider-price"></div>

Of course the Javascript above will print something like "£0 - £5000000" into the "amount" input box.

I've been looking at a way to extend the Javascript so that it formats the numbers with thousand separators (i.e. "£0 - £5,000,000"). I have found several Javascript functions that will do this, but I can't seem to call them within the jQuery function block.

For example this function would be perfect http://www.mredkj.com/javascript/nfbasic.html but I cant seem to ref开发者_开发问答erence it before printing the numbers into the input box string.

I'm sure there must be a simple solution to this.


try this....

slide: function(event, ui) {       
 $("#amount").val('£' + addCommas(ui.values[0]) + ' - £' + addCommas(ui.values[1]));
}



//.....


function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


function commafy(val) {
    return String(val).split("").reverse().join("")
                      .replace(/(.{3}\B)/g, "$1,")
                      .split("").reverse().join("");
}

From: http://twitter.com/ded/status/13621796430

Usage:

commafy(5000000); // => 5,000,000
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜