Search code examples
javascripthtmlhref

Javascript checking if two let variables are null or empty


I'm trying to send an email using the html form. I'm having a problem when trying to check if two let variables are null, because even beign these variables empty, it always sends an email.

<script>
  document.addEventListener("DOMContentLoaded", function() {
    document.querySelector("#send_message_button").addEventListener("click", function() {
      let email_subject = document.querySelector("#subject").value;
      let email_body = document.querySelector("#text").value;
      let email_to = "[email protected]";
      if (!email_subject && !email_body)
      {
        location.href = 'mailto:'+email_to+'?subject='+email_subject+'&body='+email_body;
      }
    });
  });
</script>

Solution

  • You are setting your logic inverted, You need to replace

    !email_subject && !email_body with email_subject && email_body

    but you should also check for whitespaces by using the trim() method.

    function isEmpty(value) {
        return (value == null || value.trim().length === 0);
    }
    
    document.addEventListener("DOMContentLoaded", function () {
        document.querySelector("#send_message_button").addEventListener("click", function () {
            let email_subject = document.querySelector("#subject").value;
            let email_body = document.querySelector("#text").value;
            let email_to = "[email protected]";
            if (isEmpty(email_subject) || isEmpty(email_body)) return;
    
            location.href = 'mailto:' + email_to + '?subject=' + email_subject + '&body=' + email_body;
        });
    });