How can I show each input after the checkbox with Jquery hide/show for multiple fields?
The HTML is correct and if the second function is removed from the JS code this will work (see demo on jsfiddle) with the first checkbox and input... but, I don't know how to write the Jquery code for multiple fields for this HTML structure.
Is there a way to make it work correctly with less JS code, like in a single function and keep it easy for adding multiple fields (#3, #4, ... N)
HTML:
<input type="checkbox" id="trigger" name="showhidecheckbox">show/hide input #1
<div id="showthis">
<input type="text" id="hidden_field" name="showhideinput">
</div>
<br>
<input type="checkbox" id="trigger2" name="showhidecheckbox2">show/hide input #2
<div id="showthis2">
<input type="text" id="hidden_field" name="showhideinput2">
</div>
JavaScript:
$(function() {
// Set vars
var checkbox = $("#trigger");
var hidden = $("#showthis");
// Hide fields
hidden.hide();
// checkbox event listener
checkbox.change(function() {
// See if checked, show/hide
if (checkbox.is(':checked')) {
hidden.show();
} else {
hidden.hide();
}
});
});
$(function() {
// Set vars
var checkbox = $("#trigger2);
var hidden= $("#showthis2);
// Hide fields
hidden.hide();
// checkbox event listener
checkbox.change(function() {
// See if checked, show/hide
if (checkbox.is(':checked')) {
hidden.show();
} else {
hidden.hide();
}
});
});
Aucun commentaire:
Enregistrer un commentaire