JSFiddle - React, Tailwind, and code Playground

by Bhushan Kawadkar

HTML

<select name='category'>
    <option value='category1'>Category1</option>
    <option value='category2'>Category2</option>
</select>

<select name='state' class='state'>
    <option value='state1' class='cities_state1'>State1</option>
    <option value='state2' class='cities_state2'>State2</option>
</select>

<select name='city' class='cities' id='cities_state1'>
    <option value='0'></option>
    <option value='city_1_in_state1'>City 1 in state1</option>
    <option value='city_2_in_state1'>City 2 in state1</option>
</select>

<select name='city' class='cities' id='cities_state2'>
    <option value='0'></option>
    <option value='city_1_in_state2'>City 1 in state2</option>
    <option value='city_2_in_state2'>City 2 in state2</option>
</select>

CSS

.cities {
    display: none;
}

JavaScript

$(document).ready(function() {
    //set initial code when page loads
    //set state1 selected
    $('.state').val('state1');
    //get class value for selected state and use it to select city
    var city = $('.state option:selected').attr('class');

    //Hide other cities list not of selected state
    $('.cities').hide();

    //Show cities list of selected state
    $('#' + city).show();

    //manipulate value of city select
    $('.cities').val('city_1_in_state1');

    //Add state select box listern    
    $('.state').change(function() {

    //get the class attribute of option selected in state select element
    var city = $('.state option:selected').attr('class');

    //Hide other cities list not of selected state
    $('.cities').hide();
        
    //Show cities list of selected state
    $('#' + city).show();
        $('#' + city).find('option:not(:empty):first').prop('selected',true);
   });
});