当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to auto select a particular option

问题描述:

My site uses a currency converter (shopify) and even though my store accepts GBP I want to auto-select the currency USD so that upon entereing the site, prices are converted to USD

The following is my currency converter code

<label for="currencies">Currency converter </label>

<select id="currencies" name="currencies">

{% capture codes %},USD,EUR,GBP,CAD,ARS,AUD,BBD,BDT,BSD,BHD,BRL,BOB,BND,BGN,MMK,KYD,CLP,CNY,COP,CRC,HRK,CZK,DKK ,DOP,XCD,EGP,XPF,FJD,GHS,GTQ,GYD,GEL,HKD,HUF,ISK,INR,IDR,NIS,JMD,JPY,JOD,KZT,KES,KWD,LVL,LTL,M XN,MYR,MUR,MDL,MAD,MNT,MZN,ANG,NZD,NGN,NOK,OMR,PKR,PYG,PEN,PHP,PLN,QAR,RON,RUB,SAR,RSD,SCR,SGD ,SYP,ZAR,KRW,LKR,SEK,CHF,TWD,THB,TZS,TTD,TRY,UAH,AED,UYU,VEB,VND,ZMK,{% endcapture %}

{% assign supported_codes = settings.supported_currencies | split: ' ' %}

<option value="{{ shop.currency }}" selected="selected">{{ shop.currency }}</option>

{% for code in supported_codes %}

{% if code != shop.currency and codes contains code %}

<option value="{{ code }}">{{ code }}</option>

{% endif %}

{% endfor %}

</select>

How can I auto-select USD to show?

网友答案:

You could easily do this with javascript like this:

http://jsfiddle.net/83wHb/

Basically you want to run a script onload that sets the value of currencies to USD.

Ideally you'd wanna run the script onload, or right after the select element is rendered.

<script>
document.getElementById('currencies').value = "USD";
//console.log('current value selected: ' + document.getElementById('currencies').value);
</script>

Alternatively (and probably better), you could do it server side like this:

<label for="currencies">Currency converter </label>
<select id="currencies" name="currencies">
    {% capture codes %},USD,EUR,GBP,CAD,ARS,AUD,BBD,BDT,BSD,BHD,BRL,BOB,BND,BGN,MMK,KYD,CLP,CNY,COP,CRC,HRK,CZK,DKK    ,DOP,XCD,EGP,XPF,FJD,GHS,GTQ,GYD,GEL,HKD,HUF,ISK,INR,IDR,NIS,JMD,JPY,JOD,KZT,KES,KWD,LVL,LTL,M    XN,MYR,MUR,MDL,MAD,MNT,MZN,ANG,NZD,NGN,NOK,OMR,PKR,PYG,PEN,PHP,PLN,QAR,RON,RUB,SAR,RSD,SCR,SGD    ,SYP,ZAR,KRW,LKR,SEK,CHF,TWD,THB,TZS,TTD,TRY,UAH,AED,UYU,VEB,VND,ZMK,{% endcapture %}
      {% assign supported_codes = settings.supported_currencies | split: ' ' %}
      <option value="{{ shop.currency }}" >{{ shop.currency }}</option>
      {% for code in supported_codes %}
        {% if code != shop.currency and codes contains code %}
           {% if code == 'USD' %}
              <option value="{{ code }}" selected="selected"> {{ code }}</option>
           {% else %}
              <option value="{{ code }}">{{ code }}</option>
           {% endif %}
         {% endif %}
      {% endfor %}
</select>
分享给朋友:
您可能感兴趣的文章:
随机阅读: