JSFiddle - React, Tailwind, and code Playground
HTML
<form action="/AdminAssets/SelectCategory/1" class="categoryform" method="post">
<select class='parent' name='parent' size='10'>
<option value='1'>Category 1 -></option>
<option value='2'>Category 2 -></option>
</select>
<select class='child' id='child' size='10'>
<option class='sub_1' value='5'>Custom Subcategory 1.1</option>
<option class='sub_1' value='3'>Subcategory 1.1</option>
<option class='sub_2' value='4'>Subcategory 2.1</option>
</select>
<br/>
<label for="CategoryId">Category number</label>
<input id="CategoryId" maxlength="5" name="CategoryId" style="width: 35px;" type="text" value="" />
</form>
JavaScript
function cascadeSelect(parent, child, childVal) {
var childOptions = child.find('option:not(.static)');
child.data('options', childOptions);
parent.change(function () {
childOptions.remove();
child
.append(child.data('options').filter('.sub_' + this.value))
.change();
})
childOptions.not('.static, .sub_' + parent.val()).remove();
if (childVal != '') {
var classAttribute = child.find('option[value="' + childVal + '"]:first').attr('class');
alert(classAttribute);
var parentValue = classAttribute.substr(4);
parent.val(parentValue).change();
child.val(childVal);
$('.categoryform').find('#CategoryId').val(childVal);
}
}
$(function () {
$('.categoryform').find('.child').change(function () {
if ($(this).val() != null) {
$('.categoryform').find('#CategoryId').val($(this).val());
}
});
});
$(function () {
cascadeForm = $('.categoryform');
parentSelect = cascadeForm.find('.parent');
childSelect = cascadeForm.find('.child');
cascadeSelect(parentSelect, childSelect, '4');
});