user3360442 user3360442 - 14 days ago 9
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") &&
$("#showspoed").hide("fast");
} else if ($('#type2').is(':checked')) {
$("#showstoring").hide("fast") &&
$("#showonderhoud").hide("fast") &&
$("#showspoed").show("fast");
} else if ($('#type0').is(':checked')) {
$("#showstoring").hide("fast") &&
$("#showonderhoud").show("fast") &&
$("#showspoed").hide("fast");
} else {
$("#showstoring").hide("fast") &&
$("#showonderhoud").hide("fast") &&
$("#showspoed").hide("fast");
}
});

Answer

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='"+ this.dataset.show +"']").show(260);
});
[data-content]{display:none;} /* hide initially */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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>