Skip to main content

This is a basic example of how to dynamically add new options to your select drop down without reloading the page.  I’m not saving these in the database, but it’s pretty easy to add in functionality to do so.  I may provide a tutorial on that in the future, but this should get you started.

HTML:

<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 col-md-4">
                        <select name="list" id="category" class="form-control">
                            <option value="">Select an option</option>
                            <option value="1">Option 1</option>
                            <option value="2">Option 2</option>
                            <option value="3">Option 3</option>
                            <option value="4">Option 4</option>
                        </select>
                    </div>

                    <div class="form-group col-md-4">
                        <input type="text" name="message" required id="message" class="form-control"/>
                    </div>

                    <div class="form-group col-md-4">
                        <button class="btn btn-default" id="add_category">Add select option</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

jQuery:

<script>
        //On page load set the next ID to be used in the option value
        var catID = 5;
        
        //Look for the click on the Add select option
        $("#add_category").on("click", function() {
            
            //Grab the new category name from the message input box
            var newCat = $('#message').val();
            
            //Add the new option to the select, both the value and name
            $( "#category" ).append("<option value='" + catID + "'>" + newCat + "</option>");
            
            //Clear out your input box after submission so you can then add more if desired
            $('#message').val('');
            
            //Increase by 1 the catID variable so if you add more categories to the select you won't have conflicting IDs
            catID++;
        });
    </script>

I’ve commented on the jQuery script above so you know what each piece is doing.

You can view a working demo of this here.  Keep in mind we are not storing these in the database so if you reload the page your new categories will be gone.

Leave a Reply