How to dynamically populate 2nd select list based on the first option with express handlebars, materialise, jQuery and ajax?

Viewed 133

I know there's heaps of threads around for this topic but I can't seem to find one that is similar to my case. A lot have been to do with static data.

So what I want to do is, let the user pick an option on the 1st select list, then based on the value, it will populate whatever is related to that selection.

I'm trying to append an "option" tag with the value and text for each element in the exercise array but my 2nd drop down list is not showing the options at all.

I'm using express for my routes and for this particular route, I want to use ajax to populate the 2nd dropdown. I've tried a lot of things for hours and I can't seem to work it out. I'm new to node and jQuery.

this is my index.hbs file:

<div class="row">
            <div class="input-field">
                <select id="program" name="program">
                    <option value="" disabled selected>select..</option>
                    {{#each programs}}
                    <option value="{{_id}}">{{this.name}}</option>
                    {{/each}}
                </select>
                <label>Programs</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field">
                <select id="dayOfWeek" name="dayOfWeek">
                    <option value="" disabled selected>select..</option>

                </select>
                <label>Day Of Week</label>
            </div>
        </div>

Code in my script:

$(document).ready(function () {
        //materialize initialization
        $('.sidenav').sidenav();
        $('select').formSelect();
        $('#program').on('change', function () {
            const programId = ($('#program').val());

            $.ajax({
                type: 'GET',
                url: `/exercises/${programId}`,
                dataType: 'json'
            }).done((program) => {
                console.log(program.exercises)
                const exercises = program.exercises;
                for (e in exercises) {
                    $('#dayOfWeek').append('<option>').val(exercises[e]._id).text(exercises[e].name)
                }
            });
        });
    });

Any help is much appreciated.

0 Answers
Related