Chaining multiple Select2 together

后端 未结 2 1939
借酒劲吻你
借酒劲吻你 2020-12-16 06:10

Trying to make two chained auto populating select fields using select2 plugin The first select contains countries names(static select) and the second shows the states of the

2条回答
  •  孤街浪徒
    2020-12-16 06:45

    A Select2 can be chained in the same way that a standard when the value changes, and let Select2 handle searching locally. This would be similar to how you are currently trying to do it, but may suffer from issues when there are a large number of options that can be selected in the second . This requires that you have a dynamic endpoint that can handle retrieving the items for the second select as well as filtering them when searching, so it's not always feasible.

    If you already have an endpoint like this that supports filtering, this is a more responsive option as the user doesn't have to necessarily wait for all options to be retrieved before they can select an option from the second before you call .select2({data:[]}) a second time. Select2 doesn't automatically remove the tags it generates with data, so you need to do that on your own.

  • When you change the value of the after you change it.

  • The JSON that you provide in your question does not appear to be valid. Now I'm not sure if that is just because you are giving it as an example, but I would check your JSON response with JSONLint just to ensure that it is valid.

  • The code for the second option would be similar to

    $("#first").select2({
      placeholder: 'Select a number range'
    });
    
    $("#second").select2({
      placeholder: 'Select a number',
      ajax: {
        url: http://localhost/CodeIgniter/countries/get_state/',
        type: 'POST',
        data: function (params) {
          return {
            id: $("#first").val(),
            search: params.term
          }
        }
      }
    });
    

    And this can be tested at the following jsbin, which mocks the response using a range of numbers (similar to the other example): http://jsbin.com/gihusohepe/1/edit?html,output

提交回复
热议问题