admin管理员组

文章数量:1414933

Get maximum 13 numbers in an input type text box but if user presses 14 number as decimal, only then it should allow maximum 16 numbers.

HTML:

<input type="text" maxlength="15" onkeyup="checkCurrency(this)"/>

script:

    function checkCurrency(ctrl) {
        ctrl.setAttribute('maxlength', '16');
        var currency = ctrl.value.replace(/[,]+/g, '');
        var valid = /^\d{0,13}(\.\d{0,2})?$/.test(currency),
        val = currency;
        if (valid) {                
            ctrl = val;
        } else {             
            ctrl.setAttribute('maxlength', '13');                
        }
    };   

Now, it works fine when 14th place is a decimal(.),but please put any integer on 14th place and see the difference.

Get maximum 13 numbers in an input type text box but if user presses 14 number as decimal, only then it should allow maximum 16 numbers.

HTML:

<input type="text" maxlength="15" onkeyup="checkCurrency(this)"/>

script:

    function checkCurrency(ctrl) {
        ctrl.setAttribute('maxlength', '16');
        var currency = ctrl.value.replace(/[,]+/g, '');
        var valid = /^\d{0,13}(\.\d{0,2})?$/.test(currency),
        val = currency;
        if (valid) {                
            ctrl = val;
        } else {             
            ctrl.setAttribute('maxlength', '13');                
        }
    };   

Now, it works fine when 14th place is a decimal(.),but please put any integer on 14th place and see the difference.

Share Improve this question edited Apr 18, 2014 at 11:04 nanobash 5,4987 gold badges40 silver badges56 bronze badges asked Apr 18, 2014 at 11:00 ShivamShivam 831 gold badge1 silver badge11 bronze badges 9
  • I've seen this type of question on SO just today>>> – Bhojendra Rauniyar Commented Apr 18, 2014 at 11:02
  • your code is working what else do u want – Pratik Joshi Commented Apr 18, 2014 at 11:02
  • not working means - when 14th place is an integer then it shows the 14th value and then it is trimmed so it looks like a blink. – Shivam Commented Apr 18, 2014 at 11:08
  • @C-link , this type of Ununderstandable Question? – Pratik Joshi Commented Apr 18, 2014 at 11:11
  • yes but solution with jquery – Bhojendra Rauniyar Commented Apr 18, 2014 at 11:12
 |  Show 4 more ments

6 Answers 6

Reset to default 0

Try this..

HTML

<input id="a" type="text" maxlength="15" />

JS

$('#a').keypress(function (event) {
      if ($('#a').val().length < 14) {
          if (event.keyCode != '110' && event.charCode != '46') {
              $('#a').attr('maxlength', '13');
          } else if (event.keyCode == '110' || event.charCode == '46') {
              $('#a').attr('maxlength', '16');
          } 
      }
});

Why don't you just convert the number to a string, check the length and last substring for a period, and adjust the maxlength accordingly

function checkCurrency(ctrl) {
    var x = ctrl.value.toString();
    var size = x.length;
    if (x.substring(size-1) == "." && size >= 14) {
        ctrl.maxlength = 16;
    } else {
        ctrl.maxlength = 13;
    }
}

You can Do Something Like This

HTML

<input type="text" id="inp">

JQuery

    $('input').attr('maxLength','13').keyup(

     function (){
     if(this.value.contains('.'))
         $(this).attr('maxLength','16');
    else
        $(this).attr('maxLength','13');
    });

and dont forget to add JQuery reference.

EDIT: Code edited as you donot want the text to get blinked.

my 2 cents

HTML

<input type="text" maxlength="13"/>

JS

$('input').keydown(function (event) {
    $(this).data('previous', $(this).val());
    if ((event.keyCode == 110) || (event.keyCode == 190)) {
        $(this).attr('maxlength', 16);
    }
});
$('input').keyup(function (event) {
    if ( ! /^\d{0,13}(\.\d{0,2})?$/.test($(this).val())) {
        $(this).val($(this).data('previous'));
    }
});

JSFiddle

I never think that a string parison is better than a regular expression test (when it's a number question (absolutely when it's a decimal question)). I'm fairly experienced with problems on user input, so I always prefer use regular expressions to do exactly this kind of input behavior, because Its performance is always fast, more reliable, and more easy to maintenance.

I made a "input backup" behavior to always back the last valid insertion. So, for your exactly need, here is a plete example (I kept your Regex): fiddle

jQuery Code

var varRegex = /^\d{0,13}(\.\d{0,2})?$/;
var varLastValidValue = "";

$(function ()
{
    $('#SpecialInput').keyup(function ()
    {
        if (!varRegex.test($(this).val()))
            $(this).val(varLastValidValue);

        else
            varLastValidValue = $(this).val();
    });
});

Different from other answers, my have the advantage to force only 2 decimal numbers (Any where). On the server side, I think it's essential (And I believe that it's why you are putting a limitation on the input. You are reflecting the format of stored data from DataBase, right!?).


Is important note that this code only works (as It is) for 1 input. For multiple inputs in a same page, a simple approach would use elements attribute, or some thing like that to store the "LastValidValue".

(I know that the perfection would be listen the 'onkeydown' event, and block the user input. But It will use a little more advanced code, and I want to make it simple)


Hope I helped!

Try this out:

HTML code:

<input type="text" maxlength="13" />

And the jQuery:

<script src="http://ajax.googleapis./ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script>
$("input").keypress(function(e)
{
    string = $('input').val();
    length = string.length;
    if (length == 13){
        if (e.which == 46){
            $("input").attr('maxlength', 16);
        }
    }
});
</script>

本文标签: javascriptdynamically set length of an input type textbox in jquery or javacscriptStack Overflow