简体   繁体   中英

JQuery Else condition is always true

I have 4 fields in a search form namely From Date, To Date, Material and Requisition Number.

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. This will also help to check conditions when they are null or undefined. You should take a look at Javascript coerscion . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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