The situation is such as removing spaces on the fly from the beginning and end of the line, everything works for me only the problem is such that let's say I will enter a "test" then it will be entered just as "trial" spaces are cut off, but I will enter a "test message" then after the first words put a space and it is cut off, how do i fix it?

name_z = $('input[name=name_otprav]'); // Π’Ρ‹Π±ΠΈΡ€Π°Π΅ΠΌ ΠΏΠΎΠ»Π΅ Π²Π²ΠΎΠ΄Π° ΠΈΠΌΠ΅Π½ΠΈ var form_glav_input_error_name = $("#form_glav_input_error_name"); // Π’Ρ‹Π±ΠΈΡ€Π°Π΅ΠΌ Π±Π»ΠΎΠΊ ΠΏΠΎΠ΄ ошибки Π²Π²ΠΎΠ΄Π° ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΠΈ name_z.live("keyup", function(){ // ΠŸΡ€ΠΈ Π½Π°ΠΆΠ°Ρ‚ΠΈΠΈ Π½Π° ΠΊΠ½ΠΎΠΏΠΊΡƒ срабатываСт функция var name_l_val = $.trim(name_z.val()); // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ тСкст Π²Π²Π΅Π΄Ρ‘Π½Π½Ρ‹ΠΉ Π² ΠΏΠΎΠ»Π΅ Π²Π²ΠΎΠ΄Π° ΠΈΠΌΠ΅Π½ΠΈ ΠΈ отсСкаСм ΠΏΡ€ΠΎΠ±Π΅Π»Ρ‹ var name_l_val_pro = name_z.val(name_l_val); // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ Π±Π΅Π· ΠΏΡ€ΠΎΠ±Π΅Π»ΠΎΠ² var name_l_val_trim = name_z.val(); // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ тСкст Π²Π²Π΅Π΄Ρ‘Π½Π½Ρ‹ΠΉ Π² ΠΏΠΎΠ»Π΅ Π²Π²ΠΎΠ΄Π° ΠΈΠΌΠ΅Π½ΠΈ Π±Π΅Π· ΠΏΡ€ΠΎΠ±Π΅Π»ΠΎΠ² var name_l = name_l_val_trim.length; // Π‘Ρ‡ΠΈΡ‚Π°Π΅ΠΌ сколько символов Π²Π²Π΅Π΄Π΅Π½ΠΎ if (name_l == 0) { var name_otprav = "ΠœΠΈΠ½ΠΈΠΌΡƒΠΌ 2 символа, максимум 20 символов"; form_glav_input_error_name.text(name_otprav); } if (name_l == 1) { var name_otprav = "ПолС ΠΈΠΌΠ΅Π½ΠΈ Π΄ΠΎΠ»ΠΆΠ½ΠΎ ΡΠΎΡΡ‚ΠΎΡΡ‚ΡŒ ΠΌΠΈΠ½ΠΈΠΌΡƒΠΌ ΠΈΠ· 2 символов"; form_glav_input_error_name.text(name_otprav); } if (name_l > 20) { var name_otprav = "ПолС ΠΈΠΌΠ΅Π½ΠΈ Π΄ΠΎΠ»ΠΆΠ½ΠΎ ΡΠΎΡΡ‚ΠΎΡΡ‚ΡŒ максимум ΠΈΠ· 20 символов"; form_glav_input_error_name.text(name_otprav); } if (name_l <= 20 && name_l >= 2) { var name_otprav = "<font color='green'>ПолС ΠΈΠΌΠ΅Π½ΠΈ Π·Π°ΠΏΠΎΠ»Π½Π΅Π½ΠΎ Π²Π΅Ρ€Π½ΠΎ</font>"; form_glav_input_error_name.html(name_otprav); var name = name_z.val(); } }); 

    2 answers 2

    For starters, forget about the .live () method, and use the .on () method instead . And tell me, why do you need such difficulties? If you need to get the value of the field with extra spaces cut off at the edges, then after the user has finished entering data, simply use the $ .trim () function ;

    • Thanks for on ()! And why do I need. Explains This is in order to be able to keep track of everything in reality, of course you can cut off spaces when you click on a button, it’s simple, but how to make it work as I described above? that is the question. - dimka1judo
    • one
      β€œTrack in reality” will be few, as most people, while typing, look at the keyboard, not at the screen. Inexperienced users will introduce any non-standard behavior into a stupor. I would check in half a second-second after the last character was entered. And I would not change anything in the text, I would just display a warning. - beardog

    It is necessary to memorize before trimming, whether a space was entered, and after entering each character to check whether the space was not last entered. Like this: http://jsfiddle.net/jbqP5/