Reputation: 14980
I want to show some input checkbox inside a form only if a certain other checkbox is checked.
I´ve read about .show() and .hide() but I want to do it changing the css selector.
My problem is that the hidden selector isn't hidden at all: It is printed out without any regard of the checkbox.
Please note that this is just a test, I'm learning jQuery and wanted to try it out.
This is what I've tried (JSfiddle)
<form name="ejemplo">
<input type="checkbox" name="checkbox1" id="idCheckbox1" value="check" checked>Sí?
<input type="checkbox" name="checkbox2" id="idCheckbox2" value="check">No
<div id="ocultar">
<input type="checkbox" name="checkbox3" id="idCheckbox3" value="check">Tal Vez</div>
</form>
//Usamos jQuery para mostrar un elemento condicionalmente
if ( $("input:checkbox[id=idCheckbox2]:checked") )
$("#ocultar").css("display","inline");
else
$("#ocultar").css("display","none");
Upvotes: 0
Views: 68
Reputation: 38102
Since id
is unique you can use
$("#idCheckbox2")
instead of
$("input:checkbox[id=idCheckbox2]")
To check if the checkbox is checked, you can use .is():
if($("#idCheckbox2").is(":checked"))
$("#ocultar").css("display","inline");
else
$("#ocultar").css("display","none");
You also need to use .change() event to keep track when your checkbox has been changed and shorten your code using ternary operator:
$('#idCheckbox2').change(function () {
$("#ocultar").css("display", this.checked ? 'inline' : "none");
}).change();
The .change()
at the end is used to trigger the change()
event on page load and execute the code if your checkbox has been checked by default.
Upvotes: 2
Reputation: 388316
You need to use a change event handler so that the display properties will up updated based on checking/unchecking of the checkbox
$('#idCheckbox2').change(function(){
$("#ocultar").css("display", this.checked ? 'inline':"none");
}).change();//used to set the initial state based on checkbox value
Demo: Fiddle
You can even use .toggle() to simplify the code like in this fiddle
Upvotes: 2