只显示所选选项的国家代码。

huangapple go评论55阅读模式
英文:

show only country code on selected option

问题

我只想在选择任何选项时,仅显示国家代码而不显示国家名称。我该如何实现这一点,请帮助我。

英文:

I have a list of country in select optio have country code and country name like:

<select class="form-control" name="phone_code">
    <option value="93">Afghanistan (+93)</option>
    <option value="358-18">Aland Islands (+358-18)</option>
    <option value="355">Albania (+355)</option>
    <option value="213">Algeria (+213)</option>
</select>

I just want that, when I select any option, it will show only country code without country name.

How can I achieve this, please help me out.

答案1

得分: 0

以下是使用JavaScript和jQuery实现的工作解决方案:

$(document).ready(function() {
    let defaultOptions = $("#phone_code").html(); // 存储默认选项的HTML
    $("#phone_code").change(function() {
        let countryCode = $(this).val();
        $(this).find("option:selected").text('+' + countryCode);
    }).mousedown(function() {
        // 恢复HTML中的默认选项
        $(this).html(defaultOptions);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" name="phone_code" id="phone_code">
    <option value="93">选择</option>
    <option value="93">阿富汗 (+93)</option>
    <option value="358-18">奥兰群岛 (+358-18)</option>
    <option value="355">阿尔巴尼亚 (+355)</option>
    <option value="213">阿尔及利亚 (+213)</option>
</select>
英文:

You can achieve this using Javascript or jQuery. Below is the working solution using jQuery

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

$(document).ready(function() {
    let defaultOptions = $(&quot;#phone_code&quot;).html(); // Store the default options HTML
    $(&quot;#phone_code&quot;).change(function() {
        let countryCode = $(this).val();
        $(this).find(&quot;option:selected&quot;).text(&#39;+&#39; + countryCode);
    }).mousedown(function() {
        // Restore the default options in HTML
        $(this).html(defaultOptions);
    });
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;select class=&quot;form-control&quot; name=&quot;phone_code&quot; id=&quot;phone_code&quot;&gt;
    &lt;option value=&quot;93&quot;&gt;Select&lt;/option&gt;
    &lt;option value=&quot;93&quot;&gt;Afghanistan (+93)&lt;/option&gt;
    &lt;option value=&quot;358-18&quot;&gt;Aland Islands (+358-18)&lt;/option&gt;
    &lt;option value=&quot;355&quot;&gt;Albania (+355)&lt;/option&gt;
    &lt;option value=&quot;213&quot;&gt;Algeria (+213)&lt;/option&gt;
&lt;/select&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月24日 22:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定