Home > Enterprise >  Javascript checking if two let variables are null or empty
Javascript checking if two let variables are null or empty

Time:10-16

I'm trying to send an email using the html form. I'm having a problem when trying to check if two let varibles are null, because even beign these varibles 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>

Thanks in advanced!

CodePudding user response:

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;
    });
});
  • Related