Rosamunda
Rosamunda

Reputation: 14980

Why this code doesn't hide the checkbox?

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)

HTML FORM:

<form name="ejemplo">
    <input type="checkbox" name="checkbox1" id="idCheckbox1" value="check" checked>Sí? &nbsp; &nbsp;
    <input type="checkbox" name="checkbox2" id="idCheckbox2" value="check">No &nbsp; &nbsp;
    <div id="ocultar">
        <input type="checkbox" name="checkbox3" id="idCheckbox3" value="check">Tal Vez</div>
</form>

JS

    //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

Answers (2)

Felix
Felix

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.

Fiddle Demo

Upvotes: 2

Arun P Johny
Arun P Johny

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

Related Questions