Hide/Show when checkbox is checked or unchecked

Asked

Viewed 4,673 times

2

How can I check if a checkbox field is checked, and according to its state, hide or show another input field, example:

    <label>
    <input type="checkbox" name="check" /> Clique aqui
    </label>
    <input type="optional" name="op1" />

2 answers

5


You can do it like this:

$('[name="check"]').change(function() {
  $('[name="op1"]').toggle(200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
    <input type="checkbox" name="check" /> Clique aqui
</label>
<input type="optional" name="op1" />

The script is monitoring the change event of the elements with the attribute name="check", when changed it executes the event toggle inputs with an attribute name="op1".

The toggle works as follows: When a input is hidden it will be visible, when it is visible, it will be hidden.

OBS.: The parameter 200 is a time in milliseconds that you want the action to happen, for it to create an animation during the transition, you can modify or even remove this parameter, it is up to you.

1

I made a quick code here, that would be it?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
    <input type="checkbox" name="check"  id="check" value="true"/> Clique aqui
    </label>
    <input type="optional" name="op1" id="opcao" />
<script>
    
    $("#check").click(function(){
	
		if($(this).val()=="true"){
			$("#opcao").css("visibility","hidden");
			$(this).val("false");
			}
			else{
					$("#opcao").css("visibility","visible");
					$(this).val("true");
				}
			
		
		});
    </script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.