Bootstrap Form Helper - Select country dynamically on Country picker

4.6k Views Asked by At

I'm using country picker from Bootstrap form helper: Country Picker

Problem is that i need to initialize it dynamically with a country. I'm using data-country="US" as default, anyways i need to change it on document ready function.

      <div id="country-select" class="bfh-selectbox bfh-countries" data-flags="true" data-value="US">
        <input type="hidden" value="">
        <a class="bfh-selectbox-toggle" role="button" data-toggle="bfh-selectbox" href="#">
          <span class="bfh-selectbox-option input-medium" data-option=""></span>
          <b class="caret"></b>
        </a>
        <div class="bfh-selectbox-options">
          <input type="text" class="bfh-selectbox-filter">
          <div role="listbox">
          <ul role="option">
          </ul>
          </div>
        </div>
      </div>
2

There are 2 best solutions below

3
Cemal On BEST ANSWER

use the html below to select a default country on initialize. Also add bootstrap-formhelpers.js and bootstrap-formhelpers.css to your html or your select will not be populated with data.

<form><select  id="country-select" name="country-select" class="form-control bfh-countries" data-country="US" data-flags="true"></select></form>

and to select a country after initialization,

$('#country-select').val('TN');

see the document for more options on initilization. Here's a working fiddle.

Per OP's comment The OP is using a theme using select2, quoting from there

Select2 will listen for the change event on the element that it is attached to. When you make any external changes that need to be reflected in Select2 (such as changing the value), you should trigger this event.

and therefore to reflect changes;

  $('#country-select').val('TN').trigger('change');
4
Hamza Abdaoui On

From the Example 3, you can use

$(document).ready(function(){
    $('#country-select').bfhcountries({country: 'TN'});
});

$('#LoadCountry').click(function(){
  $('#countries1').bfhcountries({country: 'TN'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-formhelpers/2.3.0/js/bootstrap-formhelpers.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-formhelpers/2.3.0/css/bootstrap-formhelpers.css" rel="stylesheet"/>


<button id='LoadCountry' class="btn">Load Countries</button>
<br><br>
<select id="countries1" class="form-control"></select>