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/