I have some fields that I want to hide if they are null. I am able to do this with:
if (json[0].incendio_edificio == null) {
$("#dIncendio_edificio").parent().parent().hide();
}
if (json[0].hvct_edificio == null) {
$("#dHvct_edificio").parent().parent().hide();
}
if (json[0].granizo_edificio == null) {
$("#dGranizo_edificio").parent().parent().hide();
}
What I want to do is put the fields inside a matrix and do the conditional inside a loop, like this:
const campos_poliza = [
[json[0].incendio_edificio, $("#dIncendio_edificio")],
[json[0].hvct_edificio, $("#dHvct_edificio")],
[json[0].granizo_edificio, $("#dGranizo_edificio")],
];
for (var x in campos_poliza){
if (x[0] == null) {
x[1].parent().parent().hide();
}
}
This doesn´t give any errors but it keeps showing null fields. How can I achieve this? The html is:
<div class="row">
<div class="col s3">
<span class="text-bold text-blue">Incendio Edificio:</span>
</div>
<div class="col s9">
<span id="dIncendio_edificio"></span>
</div>
</div>
<div class="row">
<div class="col s3">
<span class="text-bold text-blue">HVCT Edificio:</span>
</div>
<div class="col s9">
<span id="dHvct_edificio"></span>
</div>
</div>
<div class="row">
<div class="col s3">
<span class="text-bold text-blue">Granizo Edificio:</span>
</div>
<div class="col s9">
<span id="dGranizo_edificio"></span>
</div>
</div>
CodePudding user response:
When you use for (var x in campos_poliza)
, x
is the index of array, which is 0, 1, 2...
This might be what you need:
for (var x of campos_poliza) {
if (x[0] == null) {
x[1].parent().parent().hide();
}
}
Or
campos_poliza.forEach(x => {
if (x[0] == null) {
x[1].parent().parent().hide();
}
});
CodePudding user response:
Why not toggle if existing
const obj = [{ incendio_edificio:null, hvct_edificio : "not null", granizo_edificio : null }]
Object.entries(obj[0]).forEach(([key,val]) => {
const sel = `#d${key.slice(0,1).toUpperCase()}${key.slice(1)}`;
console.log(key,val,sel)
const $elem = $(sel)
if ($elem) $elem.closest(".row").toggle(val!=null)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="row">
<div class="col s3">
<span class="text-bold text-blue">Incendio Edificio:</span>
</div>
<div class="col s9">
<span id="dIncendio_edificio"></span>
</div>
</div>
<div class="row">
<div class="col s3">
<span class="text-bold text-blue">HVCT Edificio:</span>
</div>
<div class="col s9">
<span id="dHvct_edificio"></span>
</div>
</div>
<div class="row">
<div class="col s3">
<span class="text-bold text-blue">Granizo Edificio:</span>
</div>
<div class="col s9">
<span id="dGranizo_edificio"></span>
</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>