Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show/hide DIV by clicking radio button?

By default the both DIV's should be hidden. By selecting the radio button, have to show the appropriate DIV (following its #ID).

Below is my code:

<input type="radio" name='thing' value='valuable' id="bank"/>
<input type="radio" name='thing' value='valuable' id="school"/>

<div id="bank" class="none">Bank</div>
<div id="school" class="none">School</div>

<style> .none { display:none; } </style>

But we have to show only one div at a time. Is it possible?

like image 564
Umarfaruk M Avatar asked Nov 28 '22 17:11

Umarfaruk M


2 Answers

This can be done using CSS.

Note: The <div>s must be general siblings of the <input> element.

HTML:

<form>
    <input type="radio" name="showGreen"> Green
    <input type="radio" name="showRed"> Red
    <div id="green">I am the green div.</div>
    <div id="red">I am the red div.</div>
</form>

CSS:

#green, #red {
    display: none;
    padding: 10px;
}

#green {
    background-color: #6f6;
}

#red {
    background-color: #f44;
}

input[name="showGreen"]:checked ~ #green,
input[name="showRed"]:checked ~ #red {
    display: block;
}

JSFiddle: http://jsfiddle.net/Ly56w/

like image 174
uxcode Avatar answered Dec 05 '22 14:12

uxcode


You can use the data-* attribute here like:

HTML

<input type="radio" name='thing' value='valuable' data-id="bank" />
<input type="radio" name='thing' value='valuable' data-id="school" />

JS

$(':radio').change(function (event) {
    var id = $(this).data('id');
    $('#' + id).addClass('none').siblings().removeClass('none');
});

WORKING FIDDLE DEMO

like image 21
palaѕн Avatar answered Dec 05 '22 15:12

palaѕн