Search code examples
jqueryselectrequired

jquery: when select list value is changes, date field is required


I've got a form and when the status select list is changed, the status effective date needs to be a required field.

function checkStatuses(){    
   $('.status').each(function (){  
      thisStatus = $(this).val().toLowerCase();  
      thisOrig_status = $(this).next('.orig_status').val().toLowerCase();  
      target = $(this).parents('td').nextAll('td:first').find('.datepicker');  

      if ( thisStatus  == thisOrig_status  )  
      {  
         target.val('');  
      }  
      else if( thisStatus == 'production' || thisStatus == 'production w/o appl')
      {
         target.val('<cfoutput>#dateformat(now(), "mm/dd/yyyy")#</cfoutput>').focus();
         alert('The Status Effective Date is required.');
         return false;  
      }  
      else  
      {  
         target.val('<cfoutput>#dateformat(now(), "mm/dd/yyyy")#</cfoutput>');  
         return false;  
      }  
   });  
}

The return false is not preventing my form submitting anyway. The form above is being called by another function like such:

return checkStatuses();


Solution

  • Your function right now is returning nothing. The only return statements you have are in the jQuery loop. A return false is basically a break to the $.each() loop. Which then returns to your main function (checkStatuses()) which reaches the end of the codeblock without any return statement. Having a return variable may help:

    function checkStatuses(){
       var result = true;  //assume correct unless we find faults
    
       $('.status').each(function (){  
          thisStatus = $(this).val().toLowerCase();  
          thisOrig_status = $(this).next('.orig_status').val().toLowerCase();  
          target = $(this).parents('td').nextAll('td:first').find('.datepicker');  
    
          if ( thisStatus  == thisOrig_status  )  
          {  
             target.val('');  
          }  
          else if( thisStatus == 'production' || thisStatus == 'production w/o appl')
          {
             target.val('<cfoutput>#dateformat(now(), "mm/dd/yyyy")#</cfoutput>').focus();
             alert('The Status Effective Date is required.');
             result = false;  //set to false meaning do not submit form
             return false;  
          }  
          else  
          {  
             target.val('<cfoutput>#dateformat(now(), "mm/dd/yyyy")#</cfoutput>');
             result = false;  //set to false meaning do not submit form
             return false;  
          }  
       });  
       return result;  //return the result of the checks
    }