user user - 2 months ago 7
HTML Question

Javascript: How to hide div if Label inside is empty

I would like to hide the div with the class= "form-group" if the label inside doesn't have anything to display
here is my html code:

echo'<div class="form-group">';
echo'<label for="exampleInputFile" class="tbh">'.$query2['req_1'].'</label>';
echo'<input type="file" name="my_image" accept="image/*" id="exampleInputFile"> ';
echo'</div>';


And my javascript is here:

<script type="text/javascript">
if($('label.tbh:empty')){
$('div.form-group').hide();
}
</script>


Is there any other way to do that? In my code it doesn't seem to work.
Thanks in advance for the help.

Answer

If you are using jQuery, you may do it by that way:

$("div.form-group label.tbh:empty").parent().hide();

It's a right way to do in inside document.ready callback:

$(document).ready(function(){
    $("div.form-group label.tbh:empty").parent().hide()
});

To include jQuery, add

echo '<script src="https://code.jquery.com/jquery-3.1.1.js"></script>';

to head of your script.

But it seems like you are using PHP or something like at your backend side? If so, you may do it on server-side code like this:

if(strlen($query2['req_1']) == 0)
{
    echo'<div class="form-group">';
    echo'<label for="exampleInputFile" class="tbh">'.$query2["req_1"].'</label>';
    echo'<input type="file" name="my_image" accept="image/*" id="exampleInputFile"> ';
    echo'</div>';
}

in this case you would not transfer unneeded data to the client.