Problem when showing Html element from Javascript

2

I have a table in HTML and I want to show and hide a label label that is inside a when a check is selected, by default the label is hidden, the problem is that if I put the css code in a separate file JavaScript It shows me the label label, but if I put the CSS code in the HTML if it works. Can someone help me?

I put the code to be clear.

html code of the check that calls the Js and the label that I want to show:

<input type="checkbox" id="idCheckApellidos" name="checkApellidos" value="apellidos" onclick="mostrarApellidos()" ></input>
<td>&nbsp;&nbsp;<label id="labelApe2">Apellido2:</label></td>

CSS code by which I hide the tag:

#labelApe2 {
display: none;

}

Javascript code to display the tag:

function mostrarApellidos() {

var checkeado = document.getElementById('idCheckApellidos').checked;

if (checkeado) {
    document.getElementById('labelApe2').style.display = '';
} 
else {
    document.getElementById('labelApe2').style.display = 'none';
}

}

If instead of putting the CSS in an external file, I put it in dripping if it works, but I need it to be in an external file.

example of the label with css enbedded that if it works, it is shown with the Javascript:

<td>&nbsp;&nbsp;<label id="labelApe2" style="display: none">Apellido2:</label></td>
    
asked by Francisco Pagan 19.06.2016 в 11:19
source

1 answer

1

Welcome to the SOes family, your problem is that when defining the CSS rule in the labelApe2 element. If this rule ceases to exist, it works quietly.

When using the following line:

document.getElementById('labelApe2').style.display = '';

You are removing the style of the object with labelApe2 ID, however the rules you have defined in the stylesheet remain valid.

 function mostrarApellidos() {

var checkeado = document.getElementById('idCheckApellidos').checked;
console.log(checkeado); // Aqui vemos que valor tiene la variable
if (checkeado) {
    document.getElementById('labelApe2').style.display = '';
} 
else {
    document.getElementById('labelApe2').style.display = 'none';
}

}
 /*#labelApe2 {
display: none;
}*/
 <input type="checkbox" id="idCheckApellidos" name="checkApellidos" value="apellidos" onclick="mostrarApellidos()" ></input>
<td>&nbsp;&nbsp;<label id="labelApe2" style="display:none;">Apellido2:</label></td>
    
answered by 19.06.2016 / 11:45
source