This is the code, I want that when clicking on Do you want to book? the "calendario_reservation" div is displayed, but something is wrong:
activar_reserva();
function activar_reserva(){
if(document.getElementById('activar_reserva').checked){
document.getElementById('calendario_reserva').style.display = "unset";
}else{
document.getElementById('calendario_reserva').style.display = "none";
}
}
<form action="#" method="post">
<input type="checkbox" id="activar_reserva" onclick="activar_reserva();">
<label>¿Quieres reservar?</label>
<div class="" id="calendario_reserva">
AQUI UN CALENDARIO PARA SELECCIONAR LA FECHA.
</div>
<br/>
<button type="submit" name="action" value="contestar" class="form-control fondo2 color1" style="margin-top:10px;">Enviar</button>
</form>
Welcome to the oddities of the HTML DOM.
This is not the fault of Javascript, but of the way the DOM is implemented in browsers .
HTML5 non-normatively (not recommended) allows access to any element that has a unique ID as follows:
Therefore, you have defined an element
input
like this:What has happened?
By declaring that element, window.activate_reservation becomes a valid attribute that has the same value as
document.getElementById('activar_reserva')
. The function you declared conflicts with this element and is no longer accessible. Changing the id or the name of the function, everything works.In any case, I recommend using the method
addEventListener
to handle events on the elements of your document.Verification:
Rename the function
activar_reserva
toactivarReserva
and instead of using the methodonclick
use theonchange
.The problem is that you cannot have the same name for the element id and for the function you want to perform for the element, with the same name:
Likewise, I leave you another way to write the function, in a simpler way:
One way to do this would be to call a listener and remove the method from the html
here I leave the answer with jquery
I hope it helps you