user3360442 user3360442 - 1 year ago 76
HTML Question

Effective hide & show classes

I'm wondering if the code below can be simplified/normalized into something more efficiently. The code works as it should but im thinking it could be smaller. It basicly hides and shows classes when a radio option is selected.

$("input[type='radio']").click(function () {
if ($("#type1").is(":checked")) {
$("#showstoring").show("fast") &&
$("#showonderhoud").hide("fast") &&
} else if ($('#type2').is(':checked')) {
$("#showstoring").hide("fast") &&
$("#showonderhoud").hide("fast") &&
} else if ($('#type0').is(':checked')) {
$("#showstoring").hide("fast") &&
$("#showonderhoud").show("fast") &&
} else {
$("#showstoring").hide("fast") &&
$("#showonderhoud").hide("fast") &&

Answer Source

Use data-* attributes to cross-reference buttons and elements by that data value:

var $content = $("[data-content]");

$("input[type='radio']").on("change", function() {
  $content.hide(260).filter("[data-content='"+ +"']").show(260);
[data-content]{display:none;} /* hide initially */
<script src=""></script>

<input type="radio" data-show="1" name="r">A
<input type="radio" data-show="2" name="r">B
<input type="radio" data-show="3" name="r">C
<input type="radio"               name="r" checked> Else?<br>

<div data-content="1">AAA</div>
<div data-content="2">BBB</div>
<div data-content="3">CCC</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download