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.
Using .text()
is a safer option. If the label is empty, .text()
will return an empty string and negating it will give true
. Refer to the interactive snippet with example below. I placed the relevant code in a button click handler to prove that it works after you click on it.
$('button').click(function () { if (!$('.tbh').text()){ $('.form-group').hide(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label for="exampleInputFile" class="tbh"></label> <input type="file" name="my_image" accept="image/*" id="exampleInputFile"></div> <button>Click to hide</button>
Try this:
if($('label.tbh').html() == ""){
$('div.form-group').hide();
}
You can do it like this:
/* Be sure that your dom is loaded */
$( document ).ready(function() {
/* Checking that the label is empty */
if($("label").html().length == 0) {
$('div.form-group').hide();
}
});
You can also use size()
instead of length
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.