简体   繁体   English

JQuery Else条件始终为true

[英]JQuery Else condition is always true

I have 4 fields in a search form namely From Date, To Date, Material and Requisition Number. 我在搜索表单中有4个字段,分别是“起始日期”,“截止日期”,“物料”和“申请编号”。

I want the user to choose any one field for search. 我希望用户选择任何一个字段进行搜索。 But, if the user chooses date field then both from date and to date fields should be chosen, else user should be presented with a message. 但是,如果用户选择日期字段,则应该同时选择“开始日期”和“截止日期”字段,否则应向用户显示一条消息。

Following is my code: 以下是我的代码:

if(fromdt=='' && todt=='' && matnr=='' && req_no==''){
          scl_show_alert({'msg': 'Please Select atleaset one filter.', 'type': 'warning'});
          return false;

        }
        else if((fromdt!='' && todt=='') || (fromdt=='' && todt!='')){
              scl_show_alert({'msg': 'Please Select Both From Date and To Date.', 'type': 'warning'});
              return false;
        }       
        else{
                //code for showing data
        }

The problem is that, else part executes even when all the value are blank. 问题是,即使所有值都为空白,其他部分也会执行。

try using if (formdt && todt && matnr && req_no) instead of comparing with empty string. 尝试使用if(formdt && todt && matnr && req_no)而不是与空字符串进行比较。 This will also help to check conditions when they are null or undefined. 当条件为null或未定义时,这也将有助于检查条件。 You should take a look at Javascript coerscion . 您应该看一下Javascript强制。 Javascript coerces the values to boolean equivalent when used in if condition so the falsey values will be empty string, nulll, undefined and 0 hence when you use for example if (fromdt) and if fromdt is any of the falsy values it won't enter the if case. Javascript在if条件中使用时会将值强制转换为布尔值等效值,因此falsey值将为空字符串,null,undefined和0,因此,当您使用if(fromdt)并且fromdt是任何虚假值时,它将不会输入如果是这样。

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

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