Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to refresh Select2 dropdown menu after ajax loading different content?

Tags:

jquery

ajax

php

I'm using Select2 in a combination of dropdown menus. I have one menu for "Countries" and one for "States/Provinces". Depending on the country that is chosen, the "States/Provinces" dropdown changes in content. The states/provinces are pulled with ajax from a database and then displayed this way:

$display_output = '<select style="width:350px;" tabindex="2" name="state" id="state" data-placeholder="Choose a Country..."> '; $display_output .= '<option value="" selected>Select a State</option> ';  while ($state_details = $this->fetch_array($sql_select_states)) {     $display_output .= '<option value="' . $state_details['id'] . '" ' . (($selected_value == $state_details['id']) ? 'selected' : ''). '>' . $state_details['s.name'] . '</option>'; }  $display_output .= '</select>'; 

So far, so good. All the provinces change correctly, however when it initially loads, the Select2 shows "undefined" for the states dropdown, even though I have it set as

data-placeholder="Choose a Country..." 

I'm assuming it could be because on loading, the country selected is "United States" and it populates a list of states but none of them is default or selected. Is there any other way to define a default value so that it doesn't show "Undefined"?

And another (but less important) problem is that when someone chooses "United States" for example, and then chooses "Arizona", if the person then changes to "Canada" as the country, the state of "Arizona" still stays but when opening the dropdown the provinces of Canada are selectable. Is there any way to return it to the default value temporarily when someone selects another country, until a province is chosen again?

My loading code is currently just:

<script> $(document).ready(function() { $("#state").select2(); }); </script> 
like image 203
user1227914 Avatar asked Jul 23 '13 18:07

user1227914


1 Answers

Select 3.*

Please see Update select2 data without rebuilding the control as this may be a duplicate. Another way is to destroy and then recreate the select2 element.

$("#dropdown").select2("destroy");  $("#dropdown").select2(); 

If you are having problems with resetting the state/region on country change try clearing the current value with

$("#dropdown").select2("val", ""); 

You can view the documentation here http://ivaynberg.github.io/select2/ that outlines nearly/all features. Select2 supports events such as change that can be used to update the subsequent dropdowns.

$("#dropdown").on("change", function(e) {}); 

Select 4.* Update

You can now update the data/list without rebuilding the control using:

fooBarDropdown.select2({     data: fromAccountData }); 
like image 110
SamV Avatar answered Sep 24 '22 09:09

SamV