Reputation: 47
I have 2 radio buttons. When I click on one of them new div appear. I want it to disappear when I choose the second button.
Thank you in advanced.
<p><label>Type</label><input type='radio' name='affType' value='private' class='short_filed' checked /> Private <input type='radio' name='affType' value='company' class='short_filed return'/> Company</p>
<div class="hidden">
<p><label>Name</label><input type='text' name='companyName' value='' /></p>
</div>
<script>
$(".hidden").hide(400);
$('.return').change(function(){
if(this.checked){
$('.hidden').show( "slide", 400);
}else{
$('.hidden').hide( "slide", 400);
}
});
</script>
Upvotes: 2
Views: 114
Reputation: 20250
You can simplify it to:
$('input.short_filed').change(function() {
$('.hidden').toggle( this.checked && this.value == 'company' );
}).filter(':checked').change();
So it's checking the state of the checkbox, and the value, then toggling .hidden
based on the result of that.
The .filter(':checked').change()
will trigger the change()
event on the checked checkbox when the page loads, so you don't need to call ('.hidden').hide()/show()
.
Upvotes: 0
Reputation: 10122
Have a look at the below code sample :
<p>
<label>Type</label><input type='radio' name='affType' value='private' class='short_filed' checked />
Private
<input type='radio' name='affType' id="radComp" value='company' class='short_filed return' />
Company</p>
<div class="hidden" style="display: none">
<p>
<label>Name</label><input type='text' name='companyName' value='' /></p>
</div>
<script type="text/javascript" language="javascript">
$('input[type = radio]').change(function () {
if (this.value == "company") {
$('.hidden').show("slide", 400);
} else {
$('.hidden').hide("slide", 400);
}
});
</script>
Upvotes: 0
Reputation: 2170
$(".hidden").hide(400);
$('input[type="radio"]').change(function(){
if($(this).val() == 'company'){
$('.hidden').show();
}else{
$('.hidden').hide();
}
});
Upvotes: 1
Reputation: 973
You need to change JQuery script as like below... Or try this JSFiddle LINK
<script type="text/javascript">
$(document).ready(function () {
$('.short_filed').bind('change',function () {
$('.hidden').toggle();
});
});
</script>
If you need to Hide and Show textbox on only company radio button selection and deselection then follow below code...
<script type="text/javascript">
$(document).ready(function () {
$('.return').bind('change',function () {
$('.hidden').toggle();
});
});
</script>
Upvotes: 0
Reputation: 53198
You need to change the logic, because you're only ever checking if the checkbox is checked, not its actual value.
Also, change your selector, since you're only listening to the change
event on the second radio button:
$(".hidden").hide(400);
$('input[name="affType"]').change(function(){
if($(this).is(':checked') && $(this).val() == 'company'){
$('.hidden').show();
}else{
$('.hidden').hide();
}
});
Upvotes: 0