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

前端 未结 5 1207
梦毁少年i
梦毁少年i 2020-12-21 03:53

I can manipulate a control based on the state of another control, as shown in this jsfiddle, where the state of a Checkbox alters the width and background color of a Textbox

5条回答
  •  独厮守ぢ
    2020-12-21 04:15

    You do that the same as you are doing the changes of styles:

    $('#txtbxSSNOrITIN').attr('maxlength', '2');
    

    Notice also how I replaced the selector #txtbxSSNOrITIN. That's a better and faster approach to select by id.

    $('#txtbxSSNOrITIN').attr('maxlength', '10');
    

    This is what happens if the checkbox isn't checked (just an example)

    Don't forget to cut off the value entered by the user if the maxlength attribute gets contrained

    $('#txtbxSSNOrITIN').val($('#txtbxSSNOrITIN').val().substr(0,2));
    

    That happens in the if block. Here your fiddle modified:

    http://jsfiddle.net/jy6t5oru/7/

提交回复
热议问题