Jump to content

Append Select Option with jQuery


Recommended Posts

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.


<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>

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

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


        //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
            //Increase by 1 the catID variable so if you add more categories to the select you won't have conflicting IDs

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.

The post Append Select Option with jQuery appeared first on Kansas City Web Consulting | Kansas City Web Development.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...