0

I have create and update options for a field called category. I'm using Node.jS and ejs templating. When user clicks on create, I bind values which are returned initially when the url is called. After user creates the category, I have an update button to update the previously binded categories. I used select2 multiple to select multiple categories. How do I bind the values which user has entered while creation when user clicks on update?

I'm able to retrieve the values which user has entered during creation. My problem is binding them to the field.

Here is my code:

    $(function(){
        $('#btn').click(function() {

             $('#cat').select2('data', data.categories);

        });
    });

 <div class="col-md-6 col-sm-6 col-xs-12">
              <select class="select2_multiple form-control" multiple="multiple" name="cat" id="cat" style="width: 100px;">

                    <% for(var i=0; i<data.categories.length; i++)  { %>
                    <option  value="<%=  data.categories[i]._id  %>"> <%= data.categories[i].name %></option>
                      <%  }  %>

              </select>
        </div> 

I tried the below style, even that doesn't work.

  $('#cat').select2({data: data.categories});

I tried all the solutions given here; none of them worked for me. I'm using this in a modal popup, is that causing any problem?

3
  • Possible duplicate of Dynamically add item to jQuery Select2 control that uses AJAX Jun 29, 2017 at 7:27
  • @Ryad I have updated my question. Please check it once.
    – Anirudh
    Jun 29, 2017 at 7:46
  • Actually I dont think using it in a modal would cause an obvious problem, can you make sure that your jquery selector is right(since you're using an id # make sure it's the only one present) modals can be appended more than once sometimes. Jun 29, 2017 at 7:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.