【问题标题】:Country Selector with Flags with jQuery带有 jQ​​uery 标志的国家/地区选择器
【发布时间】:2016-02-24 10:22:09
【问题描述】:

我想用国家和相关标志填充我的下拉列表。我解决了这个问题。

Html Country List with flags

但仍然无法理解,因为工作模型已损坏。 如何做到这一点?

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    你在使用引导程序吗?如果是这样,下面的链接中有一个非常有趣的表单助手

    http://www.freenetmall.com/common/jquery/FormHelpers/docs/country.html

    将满足您的情况的示例 HTML sn-p 是;

     <div class="bfh-selectbox bfh-countries" data-country="US" data-flags="true">
          <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>

    如果这没有帮助,请提供更多信息,说明您是否将标志存储在 DB 中并希望在下拉框中列出它们等?我们将不胜感激有关该方法的更多信息。

    【讨论】:

      【解决方案2】:

      这是一个基于 select2 的可搜索下拉列表:

      $(function() {
        var isoCountries = [
          { id: 'AF', text: 'Afghanistan'},
          { id: 'AX', text: 'Aland Islands'},
          { id: 'AL', text: 'Albania'},
          { id: 'DZ', text: 'Algeria'},
          { id: 'AS', text: 'American Samoa'},
          // etc
        ];
      
        function formatCountry (country) {
          if (!country.id) { return country.text; }
          var $country = $(
            '<span class="flag-icon flag-icon-'+ country.id.toLowerCase() +' flag-icon-squared"></span>' +
            '<span class="flag-text">'+ country.text+"</span>"
          );
          return $country;
        };
      
        //Assuming you have a select element with name country
        // e.g. <select name="name"></select>
      
        $("[name='country']").select2({
          placeholder: "Select a country",
          templateResult: formatCountry,
          data: isoCountries
        });
      
      });
      

      jsFiddle

      【讨论】:

      • 可以应用于表格的吗?
      • @YoussefBoudaya 是的,检查一下fiddle
      • 我需要存储国家/地区的 ID,以便我可以在我的编辑表单中再次查找它我可以将另一个值传递给 iso 国家/地区吗? @ArtemVasiliev
      • @rogue39当然,您可以在调用 .select2 之前设置相关的 $("[name='country']") 输入值,或者稍后通过 $('#my_country_id') 之类的代码.val('AL')
      猜你喜欢
      相关资源
      最近更新 更多
      热门标签