How can I restrict the number of characters entered into an HTML Input with CSS (or jQuery, if necessary)? -


i can manipulate control based on state of control, shown in this jsfiddle, state of checkbox alters width , background color of textbox.

the html is:

<input type="checkbox" id="ckbxemp" >czech bachs <input type="text" id="txtbxssnoritin"> 

the jquery is:

$(document).on("change", '[id$=ckbxemp]', function () {     if ($(this).is(":checked")) {         $('[id$=txtbxssnoritin]').css('background-color', '#ffff00');         $('[id$=txtbxssnoritin]').css('width', '24');     } else {         $('[id$=txtbxssnoritin]').css('background-color', 'green');         $('[id$=txtbxssnoritin]').css('width', '144');     } });  

but besides this, need restrict number of characters user enters textbox, according whether checkbox's state. how can that, preferably css but, if necessary, jquery?

jsfiddle

first, set maxlength like: <input type="text" id="txtbxssnoritin" maxlength="5">

$(document).on("change", '[id$=ckbxemp]', function () {      var ckd = this.checked;                        // ckd boolean      $('[id$=txtbxssnoritin]')         .attr("maxlength", ckd? 2 : 5)             // 2 characters if checked, else 5         .css({             background: ckd? '#ffff00' : "green",  // yellow if checked, else green             width: ckd? 24 : 144                   // 24px if checked, else 144         });  });  

there's still smaller issue above, , that's if i.e: user enters more 5 characters, if click checkbox value length still 5! you'll need additional strip, remove unwanted characters like:

$(document).on("change", '[id$=ckbxemp]', function () {      var ckd = this.checked;     $('[id$=txtbxssnoritin]').attr("maxlength", ckd? 2 : 5).css({        background: ckd? '#ffff00' : "green",        width: ckd? 24 : 144     }).val(function(i, v){        // if checked, slice value 2 characters:        return ckd && v.length>2 ? v.slice(0,2) : v;     });  });  

if want go-pro code build, might want additionally
prevent user feel stupid
storing last (the long one) typed value. if user clicks checkbox , realizes "well... stupid", ticking off again should old value:

jsfiddle

$(document).on("change", '[id$=ckbxemp]', function () {         var ckd = this.checked;     var $input = $('[id$=txtbxssnoritin]');     if(ckd) $input.data("oldvalue", $input.val() ); // remember current value      $input.prop("maxlength", ckd? 2 : 5).css({         background: ckd? '#ffff00' : "green",         width: ckd? 24 : 144     }).val(function(i, v){         // if checked, slice value 2 characters:         return ckd && v.length>2 ? v.slice(0,2) : $input.data("oldvalue");     });  });  

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -