I want to make a select option for size that depends on what the person chooses on a previous category select. Basically, if the person chooses clothing category then the next select will only show sizes (S,M,L,XL) and if he chooses shoes he will only be shown (33,34,44,42) you get the idea..
I use nodeJS and EJS as my template. I am NOT familiar with Jquery.
my code:
<select id='inputStyle' name='category'>
<option disabled='true'>Category</option>
<option value='shoes'>Championes</option>
<option value='shirts'>Camiseta</option>
<option value=''>sweatshirts</option>
<option value='others'>Otro</option>
</select>
</div>
<div class='inputStyle'>
<label for='size'> Size </label>
<br>
<select id='size' name='size'>
<option value=''></option>
<option value=''></option>
<option value=''></option>
<option value='others'></option>
</select>
You can do it by just using the below code. Just replace the list according to your needs.
var sizeForShoes = ["40", "44", "42", "46", "50"];
var sizeForDress = ["S", "M", "L", "XL", "XXL"];
$('#Category').change(function() {
var selectedCategory = $('#Category').val();
if(selectedCategory != ""){
//Removing current option
$('#size').find('option').remove();
var sizeList = [];
if(selectedCategory == 'shoes'){
for (var i = 1; i <= sizeForShoes.length; i++) {
var shoeSize = sizeForShoes[i];
$('#size').append($("<option></option>").attr("value", shoeSize).text(shoeSize));
}
}
else{
for (var i = 1; i <= sizeForDress.length; i++) {
var dressSize = sizeForDress[i];
$('#size').append($("<option></option>").attr("value", dressSize).text(dressSize));
}
}
}else{
//If nothing is selected then it will remove previous options
$("#size").empty();
$('#size').append($("<option></option>").attr("value", "").text("Select size"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="Category">Category</label>
<select id="Category" name="Category" >
<option value="">Select Category</option>
<option value='shoes'>Championes</option>
<option value='shirts'>Camiseta</option>
<option value='sweatshirts'>sweatshirts</option>
<option value='others'>Otro</option>
</select><br><br>
<label for="size">Size</label>
<select id="size" name="size">
<option value="">Select size</option>
</select>