开发者

Javascript algorithm adding numbers to textbox

I have 2 textboxes. One which at all times should contain 4 digits when you leave it. One which at all times should contain 10 digits when you leave it.

I need a javascript which on blur from one of the textboxes should trigger an algorithm which shall calculate the amount of characters in the just blured textbox and if the textbox does not contain the specific amount of digits, it shall add x amount of 0 (zeroes) in front of the digits untill the textbox contains the specific amount of digits in it.

What I already know is that I need to check the .length on the textboxes, but the functionality afterwards is what is bugging me.

HTML

<asp:TextBox ID="txt1" runat="server" MaxLength="4"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server" MaxLength="10"></asp:TextBox>

Javascript

<script src="jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
    var $reg = $('#txt1');
    var $acc = $('#txt2');

    $reg.blur(function () {
        if($reg.length &l开发者_Go百科t; 4)
        {
            var $miss = 4 - parseFloat($reg.length);
        }
    });

    $acc.blur(function () {
        if($acc.length < 10)
        {
            var $miss = 10 - parseFloat($acc.length);
        }
    });
});
</script>


Here's a simple alternative:

$reg.blur( function() {
    while( this.value.length < 4 )
    {
        this.value = '0' + this.value;
    }
} );

Seen in action here on jsfiddle.


Put this underneath each $miss assignment.

var padding = '';

for(var i = 0; i<$miss; i++) {
  padding += '0';
}

$(this).val(padding + $(this).val());


Create a string repeat function to pad your number with the required numbers of leading zeros.

Code coming from this thread: Repeat String - Javascript

String.prototype.repeat = function(num) {
    return new Array(isNaN(num)? 1 : ++num).join(this);
    }

Also, you don't need to use parseFloat for a length property, you need an int value anyway for your calculation.

Putting it together:

$reg.blur(function () {
       $reg.val("0".repeat(4 - $reg.val().length) + reg.val() + "");
});

Code untested, but should point you in the right direction.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜