Search code examples
javascriptjqueryhtml-selectbootstrap-form-helper

Bootstrap Form Helper - Select country dynamically on Country picker


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>

Solution

  • 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');