I have a form that needs to display a certain fieldset if any of the input elements inside that fieldset has a value.
The current code I have written only works if I have one input element with a value inside the fieldset, but if I have place a second input element, it does not work properly. I am assuming I am missing a step which needs to cycle through the elements. I am assuming I need to implement .each() somewhere.
This form will be changed from time to time by other developers, so I have to find inputs instead of targeting them directly. Thank you for any help.
Example form. I would like the fieldset with the id “toggleMe” to display, because the input “cheese” has a value, even though “bread” does not, or vice-versa:
<form action="scratch_submit" method="get" accept-charset="utf-8">
<fieldset id="toggleMe">
<label for="bread">bread</label><input type="text" name="bread" value="" id="bread">
<label for="cheese">cheese</label><input type="text" name="cheese" value="cheese is here" id="cheese">
</fieldset>
<fieldset id="neverToggle">
<label for="wine">wine</label><input type="text" name="wine" value="wine is here" id="wine">
<label for="beer">beer</label><input type="text" name="beer" value="" id="beer">
</fieldset>
</form>
my jQuery code:
$(document).ready(function() {
function toggleOptions() {
if($("#toggleMe").find('input').val()) {
$("#toggleMe").show();
} else {
$("#toggleMe").hide();
}
}
toggleOptions();
});
How about:
Basically concatenate the values of all of the child inputs and check to see if the value is not empty.
Or something a bit more traditional (and probably faster):