JSFiddle - React, Tailwind, and code Playground
by rasec
HTML
<body>
<div>
<form>
<fieldset>
<legend>Datos personales</legend>
<ul>
<li><label class="label" for="name">Nombre:</label><input type="text" required name="name" id="name" class="name" /></li>
<li><label class="label" for="email">Email:</label><input type="email" name="email" id="email" class="email" /></li>
<li><label class="label" for="url">url:</label><input type="url" name="url" id="url" class="url" /></li>
<li><label class="label">Opciones:</label>
<label for="opcionSi">Si</label><input type="radio" name="opcion" id="opcionSi" class="opcion showEnable" />
<label for="opcionNo">No</label><input type="radio" name="opcion" id="opcionNo" class="opcion hideDisabled" />
</li>
<li>
<label class="label">Opcion</label>
<select class="opcionSelect" name="select">
<option class="opcion showEnable">Opcion1</option>
<option class="opcion hideDisabled">Opcion2</option>
</select>
</li>
<li>
<label class="label">Checkbox</label><input name="checkbox" type="checkbox" class="checkbox" />
</li>
<li class="divToToggle" style="display:none;">
<label class="label">Radio</label><input type="text" name="prueba" id="prueba" />
</li>
<li class="divToToggle2" style="display:none;">
<label class="label">Select</label><input type="text" name="prueba" id="prueba" />
</li>
...
CSS
ul {
list-style: none;
}
.label {
width: 100px;
display: inline-block;
}
JavaScript
(function($) {
$.fn.extend({
showHide: function(options) {
var defaults = {
divClass: "divToToggle",
showClass: "showEnable",
hideClass: "hideDisabled"
};
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = $(this);
var divClass = o.divClass;
var showClass = o.showClass;
var hideClass = o.hideClass;
var container = jQuery("." + divClass);
var check = function() {
if ((obj.hasClass(showClass) && obj.is("input[type=radio]:checked")) || obj.find("option:selected").hasClass(showClass) || obj.is("input[type=checkbox]:checked")) {
container.showAndEnable();
} else if ((obj.hasClass(hideClass) && obj.is("input[type=radio]:checked")) || obj.find("option:selected").hasClass(hideClass) || obj.is("input[type=checkbox]:not(:checked)")) {
container.hideAndDisable();
}
};
check();
obj.change(function() {
check();
});
});
},
hideAndDisable: function() {
return this.each(function() {
var obj = $(this);
obj.hide();
obj.find("input, select, textarea").attr("disabled", "disabled");
});
},
showAndEnable: function() {
return this.each(function() {
var obj = $(this);
obj.show();
obj.find("input, select, textarea").removeAttr("disabled");
});
},
});
})(jQuery);
jQuery(function() {
jQuery(".opcion").showHide();
jQuery(".opcionSelect").showHide({
divClass: "divToToggle2"
});
...