How to use JavaScript (or JQuery) to check if an input is empty or has a certain string?
我正在创建的计算器表单上进行验证,如果用户没有在输入中输入数字,我想显示一条"请填写此字段"消息。
默认情况下,字段中有一个"0"。
因此,我要检查字段是否为空或是否具有字符串"0"。
还应该提到有一个脚本正在运行,它阻止用户输入非数字字符。
这是一系列签入if/else语句的一部分。对于这种情况,我已经有一个条件(选择用户以前的选择)。
所以我有点像:
1 2 3 4 5 6 7 8 9 10 11 12 | if ( calcChoice == 1 && $("#input-loan" ).val() =="0" ) { console.log("User input missing"); $("#input_loan" ).addClass("error" ); } else if ( calcChoice == 1 && $("#input-pay" ).val() =="" ) { console.log("User input missing"); $("#input_loan" ).addClass("error" ); } else if ( calcChoice == 2 && $("#input-loan" ).val() =="0" ) { console.log("User input missing"); $("#input_loan" ).addClass("error" ); } else if ( calcChoice == 2 && $("#input-pay" ).val() =="" ) { console.log("User input missing"); $("#input_loan" ).addClass("error" ); |
我想精简一下。我真正想要的是:
1 2 3 | if ( calcChoice == 1 && $("#input-loan" ).val() =="" ||"0"; ) { //do something; } |
有什么想法吗?
我看过以下相关问题,但还没能从他们的答案中找出答案:
如何检查javascript中的空字符串?
javascript:检查变量是否等于两个或多个值的简单方法?
字母名称
(P)你可以写(p)(P)字母名称(p)(P)如果这个方法对我好但对我有用(p)
(P)为了记录,这个Regex测试也有效。It's testing for an empty string or the string'0:(p)字母名称(P)I had tried this before but there must have been a problem elsewhere in my code.Now it works.(cheers to nils in the comments to the question for pointing out that this works).(p)
(P)Thanks for answering everyone.真的很好的解决办法Seems so obvious now to have a'0'placeholder and only test for empty.Also Akmed0zmey's solution is talius.(p)(P)I forgot to mention that there is no need to trim as I have a script running that prevents the users from putting in non-numeric characters,including spaces.I have updated the original question to include this.(p)(P)I went with rich's solution a s it most closely answers the specific problem I asked and it's a good method to retain for the future-I could have a series of strings to test against.(p)(P)Thanks!(p)
(P)A solution could be based on the following.(p)字母名称(P)As an Aside,note that instead of having a default value of"0"in your inputs you could set the EDOCX1 nipal 0 attribute of the input to 0.(p)字母名称(P)That way you don't need to check if the input is"0",and you could actually treat"0"as a valid input if desired.(p)
(P)If(Calchoice=-1&;&Amp;($…),35;Input-loan;(),val()=124;&124;(",35;input-loan");val(="0").//do some;注(p)(P)试着在这里保持神秘。Similarly,you can also use$ISMPtyobject(object)to ensure whether the value is empty or not.(p)