jQuery

Select Options Determined by Another Select’s Selection

By August 9, 2017 May 23rd, 2018 No Comments

Sometimes you may have form elements that you need to changed based on other input.  For example I have two selects on my page.  The first one if the primary goal.  The second is a multiselect box of secondary goals.  Based on the users input on the first select I don’t want them to be able to select the same item in their secondary goals.  This is how you can manipulate the second select by using onChange jQuery commands. The library used for the multiselect is Bootstrap Multiselect.

Here is the HTML of my current form:

<div class="container">
    <div class="row">
        <div class="col-md-12 text-center">
            <h1 id="setPageName"></h1>
            <div class="col-md-6 col-md-offset-3">
                <div class="form-group">
                    <label>Select a Primary Goal</label>
                    <select id="primaryGoal" class="form-control" name="companyGoal" required="">
                        <option value="">Select a Primary Goal</option>
                        <option value="1">Build a website</option>
                        <option value="2">Update a website</option>
                        <option value="3">Fix a website</option>
                        <option value="11">Build a custom web application</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Select Any Additional Goals</label>
                    <select id="stGoal" class="form-control" name="companyGoalST[]" required multiple="multiple">
                        <option value="1">Build a website</option>
                        <option value="2">Update a website</option>
                        <option value="3">Fix a website</option>
                        <option value="11">Build a custom web application</option>
                    </select>
                </div>
            </div>
        </div>
    </div>
</div>

Here’s the jQuery needed to modify the second select based on the input of the first select:

Check out the working demo here.

Leave a Reply