简体   繁体   English

jQuery修剪必填字段

[英]jQuery trim for required field

I have a textbox for user to enter full name. 我有一个文本框供用户输入全名。

Now on keyup, I call the following code (part of my changeAction call); 现在在keyup上,我调用以下代码(我的changeAction调用的一部分);

target.value = $.trim(target.value);

So the code trims the value entered by the user. 因此,代码会修剪用户输入的值。

Also since this is a required field, I use it to enable Submit button. 另外,由于这是必填字段,因此我使用它来启用“提交”按钮。

Now the issue is, because of the above code, if the user enters any space (say while typing "Mike Dennis") , he is not allowed to (after Mike) since the trim() is called ? 现在的问题是,由于上面的代码,如果用户输入任何空格(例如在键入“ Mike Dennis”时输入),则由于在trim中调用了trim(),因此不允许用户输入(在Mike之后)。

How do I fix this while ensuring that the other logic works (specifically button enabling)? 如何在确保其他逻辑正常工作(特别是启用按钮)的同时解决此问题? I cannot use "blur" event here.. 我不能在这里使用“模糊”事件。

If you are not to allow user to enter the spaces only and trim after the user finished the typing 如果您不允许用户仅输入空格并在用户完成键入后进行修剪

Here's the working fiddle http://jsfiddle.net/v8qj2suc/2/ 这是工作中的小提琴http://jsfiddle.net/v8qj2suc/2/

The HTML HTML

<input type="text" id="elementOFInterest" />

The Javascript Javascript

$("#elementOFInterest").on('keyup', function (e){ var target = e.target; if($.trim(target.value) == "" ){ target.value = ""; } }); $("#elementOFInterest").on('blur', function (e){ var target = e.target; target.value = $.trim(target.value); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM