Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle div visibility using radio buttons?

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.

like image 868
Peter Avatar asked Dec 18 '14 11:12

Peter


People also ask

How do you show and hide input fields based on radio button selection?

To show or hide an element when a radio button is selected: Add a click event handler to all input elements of type radio . Each time a radio button is selected, check if it is the button that should show the element. If it is, set the display property of the hidden element to block .

Does Onclick work with radio buttons?

You can select any radio button either by clicking on the label or by clicking on the radio button. Radio button onclick You can trigger an event to know which radio button is checked. For this select all radio buttons and add an onclick event to all button.


1 Answers

I usually tend not to use JS if possible, therefore here comes a HTML+CSS way approach.

.bussines-type .business-fields {
	display: none;
}

.bussines-type input[value="2"]:checked ~ .business-fields {
	display: block;
}
<div class="bussines-type">
	<input id="bt1" type="radio" name="type" value="1">
        <label for="bt1"> Personal</label>
	<input id="bt2" type="radio" name="type" value="2">
        <label for="bt2"> Business</label>

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

The ~ stands for any siblings, that are after the element we defined before the ~ sign.

like image 110
Akxe Avatar answered Sep 18 '22 23:09

Akxe