0

我有一个表单输入字段。

<input style="text-align:right;" type="text" name="DiversionCalc_Diversion_Rate" id="calc_dr" value="0.25%" />

我正在尝试使用 jQuery 1.7.2 基于 focusout 对其进行格式化

$('#calc_dr').focusout(function () {
    var value = $.trim($(this).val()).toString();
    if (value.indexOf("0.") === -1) {
        var $t = ("0" + value).toString();
        alert($t);
        $(this).val($t);
    }
    if (value != '' && value.indexOf("%") === -1) {
        $(this).val(value + '%');
    }
});

虽然这主要是有效的,但当我在该字段中输入 0.25 时,警报会弹出正确的 0.25,但是,$(this).val唯一显示的是 0.25

我怎样才能让它显示它在警报中显示的内容???

4

2 回答 2

1

基本思路是抓取值,操作值,然后更新 UI。关键是最后只有一个更新。

// Get the new value (strip everything but numbers and period)
var v= parseFloat($(this).val().toString().replace(/[^0-9\.]+/g, ""));

// Basic data type validation
if (isNaN(v)) v= 0;
if (v< 0) v= 0;
if (v> 100) v= 100;

// other validation updates v as needed...
doCheckDiversionRate(v);

// update UI (btw toFixed() will add a leading zero)
$(this).val(v.toFixed(2) + '%');
于 2013-12-11T19:18:59.427 回答
1

创建一个全局变量(将$t其拉出 if 循环)并分配它而不是value.

$('#calc_dr').focusout(function () {
    var value = $.trim($(this).val()).toString();
    var $t = value;
    if (value.indexOf("0.") === -1) {
        $t = ("0" + value).toString();
        alert($t);
        $(this).val($t);
    }
    if ($t != '' && $t.indexOf("%") === -1) {
        $(this).val($t + '%');
    }
});
于 2013-12-11T19:04:09.263 回答