I show or hide a div
with class='kd'
when a specific item is selected from a dropdown menu with id='id_property
':
$(document).ready(function(){
$("select#id_property").change(function(){
$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");
if(optionValue == "G"){
$(".kd").fadeIn()
} else{
$(".kd").hide();
}
});
}).change();
});
Is it possible to filter the selection from multiple dropdown menus and depending on both selections, hide or display an item?
Something like:
$("select#id_property", "select#id_name").change(function(){
$(this).find("option:selected").each(function(){
var optionValue1 = $(this).attr("value");
...
});
});
HTML
<select name="property" class="select form-control" required id="id_property">
<option value="" selected>---------</option>
<option value="G">G</option>
<option value="E">E</option>
</select>
<select name="name" class="select form-control" required id="id_name">
<option value="" selected>---------</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<div class="form-row row kd">
<label for="id_some_field" class="form-label ">Some Field</label>
<input type="text" name="some_field" maxlength="128" class="textinput textInput form-control" id="id_some_field">
</div>
Okey , what you have to do is using multiple selector separated with coma ,
,
$("select#id_property , select#id_name").on("change", function() {...})
and in the callback function use $(this).val()
to access value on each input change :
See below snippet :
$(document).ready(function() {
let selectValues = [];
$("select#id_property , select#id_name").on("change", function() {
var id = $(this).attr("id");
var optionValue = $(this).val();
selectValues[id] = optionValue;
let chars = "";
for (var key in selectValues) {
chars += selectValues[key];
}
if ( chars.includes("GG") || ( chars.includes("G") && chars.includes("A") ) ) {
$(".kd").fadeIn()
} else {
$(".kd").hide();
}
});
// for startup change
$("select#id_property , select#id_name").trigger("change");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
property :
<select name="property" class="select form-control" required id="id_property">
<option value="" selected>---------</option>
<option value="G">G</option>
<option value="E">E</option>
</select><br /><br /> name :
<select name="name" class="select form-control" required id="id_name">
<option value="" selected>---------</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="G">G</option>
</select><br /><br />
<div class="form-row row kd">
<label for="id_some_field" class="form-label ">Some Field</label>
<input type="text" name="some_field" maxlength="128" class="textinput textInput form-control" id="id_some_field">
</div>