Shivam Shivam - 5 months ago 11
jQuery Question

dynamically set length of an input type textbox in jquery or javacscript

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.

Answer

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');
          } 
      }
});
Comments