Search code examples
javascriptphpformsemailhtml-email

Hide button if mailto: is empty


I have a list of users and if they have an email they can click on a button to send an email. The thing is that I need to hide the EMAIL button if the user doesn't have a email.

Here is what i have:

<form action='/' method='get'>
<a href='mailto:<?=$user['email']?>'><button type="button" class="btn btn-dark btn-sm"><span>Email</span></button></a>
</form>

This is what i tryed but didn't work:

<a href='mailto:<?=$user['email']?>'><button id="sendmail" type="button" class="btn btn-dark btn-sm" onload="hideButton()"><span>Email</span></button></a>

<script type="text/javascript">
$(function(){
    function hideButton(){
        if(email === "mailto:"){
            $("#sendmail").show();
        }
        else {
            $("#sendmail").hide();
        }
    }
});
</script> 

I don't know how to solve it. I google this but most of the answers gives me an Error 500 when I upload to the website


Solution

  • You can do it directly in PHP just by wrapping it an if statement.

    <?php
    
    if (isset($user['email']) && trim($user['email']) !== '') {
        echo '<a href="mailto:' . $user['email'] . '">Send email</a>';
    }