I have a form containing a dropdown. Depending on the selection made in the dropdown, multiple fields should appear or hide. The jquery function, I have written, works only for one fields. If I select no in the dropdown only the title what is hidden the rest stays. I don't quite understand why. I could solve this by giving each field id another name (for example showing1, showing2, ...) and refer to this id in the function but that is a lot of repetition.
Shouldn't there be a better way?
Link to fiddle.
Thanks for the input.
## jQuery
$(document).ready(function(){
$('#showing').hide();
$('#condition').change(
function(){
if(this.value == "yes"){
$('#showing').show();
}
else {
$('#showing').hide();
}
}
)
});
### Part of the form
<div class="col-4">
<div class="d-flex">
<div class="flex-fill p-2">
<select name="playing" class="form-control" id="condition" required>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-2">
<div class="d-flex">
<div class="p-1">
<label class="p-2" for="what" id="showing" >What</label>
</div>
</div>
</div>
<div class="col-4">
<div class="d-flex">
<div class="flex-fill p-2">
<input id="showing"
type="text"
class="form-control input-text"
name="wat"
>
</div>
</div>
</div>
<div class="col-2">
<div class="d-flex">
<div class="p-1">
<label class="p-2" for="type" id="showing" >Type</label>
</div>
</div>
</div>
<div class="col-4">
<div class="d-flex">
first, you should remove id "showing" from elements and add a class name "showing" or you can add this class to the parent element of all these elements. second, you should change your id to class in jquery. and I think you didn't add the script that loads jquery.
code after edit:
$(document).ready(function(){
$('.showing').hide();
$('#condition').change(
function(){
if(this.value == "yes"){
$('.showing').show();
}
else {
$('.showing').hide();
}
}
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-4">
<div class="d-flex">
<div class="flex-fill p-2">
<select name="playing" class="form-control" id="condition" required>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-2">
<div class="d-flex">
<div class="p-1">
<label class="p-2 showing" for="what">What</label>
</div>
</div>
</div>
<div class="col-4">
<div class="d-flex">
<div class="flex-fill p-2">
<input
type="text"
class="form-control input-text showing"
name="wat"
>
</div>
</div>
</div>
<div class="col-2">
<div class="d-flex">
<div class="p-1">
<label class="p-2 showing" for="type">Type</label>
</div>
</div>
</div>
<div class="col-4">
<div class="d-flex">
<div class="flex-fill p-2">
<input
type="text"
class="form-control input-text showing"
name="type"
>
</div>
</div>
</div>
</div>