Question

I have a form input field.

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

I am attempting to format it based on focusout using jQuery 1.7.2

$('#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 + '%');
    }
});

While this mostly is working, the alert pops up the correct 0.25 when I enter .25 in the field, however, the $(this).val only ever shows .25

How can I get it to show what it's showing me in the alert???

Était-ce utile?

La solution

Make $t a global variable (pull it out of the if loop) and assign it instead of 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 + '%');
    }
});

Autres conseils

The basic idea is to grab the value, manipulate the value, then update the UI. The key being there is only one update at the end.

// 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) + '%');
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top