Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  156] [ 6]  / answers: 1 / hits: 15747  / 10 Years ago, thu, december 18, 2014, 12:00:00

I'm working on a project in which I have to toggle the visibility of a <div>.



I've got the following code:



<input type=radio name=type value=1> Personal
<input type=radio name=type value=2> Business

<div class=business-fields>
<input type=text name=company-name>
<input type=text name=vat-number>
</div>


I would like to togle the business-fields div. So, if none of the radio buttons, or the 'personal' radio button is selected: The div should be hidden. If the 'business' radio button is selected, I want it to show.



Currently, I am using this code:



$(input[name='type']).click(function() {
var status = $(this).val();
if (status == 2) {
$(.business-fields).show();
} else {
$(.business-fields).hide();
}
});


However, I was wondering if I can do this using the .toggle() function.


More From » jquery

 Answers
22

I'd suggest using the change event, and supplying a Boolean switch to the toggle() method, which will show the jQuery collection of elements if the switch evaluates to true, and hide them if it evaluates to false:





// select the relevant <input> elements, and using on() to bind a change event-handler:
$('input[name=type]').on('change', function() {
// this, in the anonymous function, refers to the changed-<input>:
// select the element(s) you want to show/hide:
$('.business-fields')
// pass a Boolean to the method, if the numeric-value of the changed-<input>
// is exactly equal to 2 and that <input> is checked, the .business-fields
// will be shown:
.toggle(+this.value === 2 && this.checked);
// trigger the change event, to show/hide the .business-fields element(s) on
// page-load:
}).change();

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<label>
<input type=radio name=type value=1>Personal</label>
<label>
<input type=radio name=type value=2>Business</label>

<div class=business-fields>
<input type=text name=company-name>
<input type=text name=vat-number>
</div>





Incidentally, note I've also wrapped the associated text, to indicate the radio-button's purpose, inside of a <label> element to directly associate that text with the <input>, so clicking the text checks the <input> automatically.



References:




[#68450] Monday, December 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;