Baumannzone
Baumannzone

Reputation: 780

dynamic options in select2 after click in some button

I'm using Select2 in my website and I need to reload (change) the options in the select with new ones after some user interaction.

I have this:

enter image description here

When I chose one day, I need to reload hours. Because each day has different hours available, like this:

enter image description here

This is my javascript object with all the info I need (No AJAX needed):

var ob = [
  {
    // Don't worry about activityId
    activityId: '1234',
    days: [
      {
        //Some date format
        id: '20161001',
        //Available hours for each day
        hours: ["10:00", "11:00"]
      },
      {
        id: '20161002',
        hours: ["10:00", "12:00"]
      }
    ]
  },
  {
    activityId: '4567',
    days: [
      {
        id: '20161003',
        hours: ["10:30", "19:00"]
      },
      {
        id: '20161002',
        hours: ["10:00", "14:00"]
      }
    ]
  }
]

I've been trying with $('#selectId').select2({ data: data }) but it only adds data to the current data available and it only works once. Second time is not adding anymore.

I want to delete options and set new ones. I'm using this variable from select2 doc's:

var data = [
  { id: 0, text: 'enhancement' }, 
  { id: 1, text: 'bug' }, 
  { id: 2, text: 'duplicate' }, 
  { id: 3, text: 'invalid' }, 
  { id: 4, text: 'wontfix' }
];

Summarize: I want to change the data of the HOURS select when the DAYS select changes.

Any help? Thanks!

Upvotes: 1

Views: 807

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

I found this question from a few years ago, and one answer suggests calling .html('') on the element before adding the new data options...

Try this:

var ob = {
    // Don't worry about activityId
    activityId: '1234',
    days: [
      {
        //Some date format
        id: '20161001',
        //Available hours for each day
        hours: ["10:00", "11:00"]
      },
      {
        id: '20161002',
        hours: ["10:00", "12:00"]
      }
    ]
  };
var days = ob.days.map(function(day) {
	return {id: day.id, text: day.id};
});

$("#e1").select2({data: days});
$("#e1").change(function(arguments) {
	var value = $("#e1").val();
  var day = ob.days.find(function(day) {
  	return day.id == value;
  });
  var selectList2 = $("#e2");
  selectList2.html('');//this will clear the existing values
  selectList2.select2({data: day.hours});
  selectList2.show(); //in case it wasn't visible before
});
.select2 {
  width:100%;
  min-width: 100px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="e1"></select>
<select id="e2" style="display: none"></select>

Upvotes: 1

Related Questions