i am trying to hide the all input field, its label, and its icon element if the content of inputs value are empty, i know how to hide all inputs with empty values using css : input:not([value]){
display:none;
}
but i cant hide the label and icons of those inputs field that are empty together as well
this is what tried by using javascript but not sure if is the right away of doing cause i am new to javascript
<script>
function hey(){
var label = document.getElementById("1");
var input = document.getElementById("2").value;
var icon = document.getElementById("3");
if (input === "") {
document.getElementById("1").style.display = "none";
document.getElementById("2").style.display = "none";
document.getElementById("3").style.display = "none";
}
</script>
<label id="1"><b>Card title</b></label>
<input type="text" id="2" placeholder="Enter a name for this card" value="" class="form-control label" name="title" required>
<i id="3" class="fa-solid fa-file-signature hidel"></i>
</div>
i also thought about giving same class names for each group of labels, inputs and icons and then hiding those elements with same class name
document.getElementByclassname(".aclassname").style.display = "none";
but it doesnt work either
2
Answers
There are many solutions for this.
For my answer, I group my form fields together in a div. So I wrapped your input in a div called formGroup. I also created a new css class called hide.
Instead of hiding each separate object, I jus grab the input element’s parent node and toggle class called hide. That way the entire group will be hidden.
With
.style
on plain.getElementById
method you can only read inline styles of an element as mentioned in the answer here: https://stackoverflow.com/a/52345935/19119712What you can do instead is use the
Window.getComputedStyle()
method to get hold of CSS properties of an element (it returns an object).Basically, all you’ve got to do is the following:
You can then make use of
compStyles
to get hold of specific style properties and manipulate those. Good luck!Note: Repeat the same process with the other elements. Also, I am not quite sure whether it’ll work with document.getElementById but you can give it a try. Ideally, it should work and if you head into any problems refer the docs I linked above.