2

I try to limit a form of input to 10 chars

var max_chars = 10;

$('input#ctl00$bc$custom_element_44').keydown( function(e){
    if ($(this).val().length >= max_chars) { 
        $(this).val($(this).val().substr(0, max_chars));
    }
});

$('input#ctl00$bc$custom_element_44').keyup( function(e){
    if ($(this).val().length >= max_chars) { 
        $(this).val($(this).val().substr(0, max_chars));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44">

But it does not seem to work, advice is sought;)

Regards Pete

peter
  • 45
  • 1
  • 1
  • 7

3 Answers3

5

Simplest approach, vanilla JavaScript. JSFiddle.

JS:

let name = document.getElementById('name');

name.addEventListener('keyup', () => {
    if (name.value.length > 10) {
        name.value = name.value.slice(0, 10);
    }
})

HTML:

<input type="text" id="name">
Lansana Camara
  • 9,497
  • 11
  • 47
  • 87
2

You can use native maxlength attribute on the input tag.

<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44" maxlength="10">
Thomas Orlita
  • 1,554
  • 14
  • 28
-3

Use below code

var max_chars = 10; $('#ctl00_bc_custom_element_44').keydown(function(e) { if ($(this).val().length >= max_chars) { $(this).val($(this).val().substr(0, max_chars)); } }); $('#ctl00_bc_custom_element_44').keyup(function(e) { if ($(this).val().length >= max_chars) { $(this).val($(this).val().substr(0, max_chars)); } });

or use max length with input tag

Jackson
  • 62
  • 8