jquery text input length control

后端 未结 3 1116
情深已故
情深已故 2021-01-06 05:48

the text input only allows three words separated by spaces, and if it exceeds 3, the user can\'t input anymore, is this possible using jQuery? I can use keyup event to liste

3条回答
  •  轮回少年
    2021-01-06 06:41

    May be something like,

    $('#myTextbox').change(
    
        function()
        {
             var input = $(this).val();
             var numberOfWords = input.split(' ').length;
             if(numberOfWords > 3)
             {
                  $(this).val(input.substring(0, input.lastIndexOf(' ')-1));
             }
        }
    );
    

    I haven't verified this code, but something like this should work.

    And yes, as mgroves said, don't forget to re-validate everything on the server.

提交回复
热议问题