[Shopify][JavaScript]住所編集の国で都道府県更新
Liquid(HTML)
国<select name="address[country]" {% if form.country != blank %}data-default-label="{{ form.country }}{% else %}data-default="Japan{% endif %}">{{ country_option_tags }}</select><br> 都道府県<select name="address[province]" data-default-label="{{ form.province }}"></select>
JavaScript
document.querySelectorAll('[name="address[country]"]').forEach((elm,index)=>{ elm.addEventListener('change',(e)=>{ onChangeCountry(e); }); }); onChangeCountry(e){ const option = e.target.querySelector('[value="'+e.target.value+'"]'); const provinceSelect = e.target.form.querySelector('[name="address[province]"]'); if(option && provinceSelect){ let options = []; const provinces = JSON.parse(option.dataset['provinces']); provinces.forEach((province,index)=>{ options.push('<option value="'+province[0]+'">'+province[1]+'</option>'); }); provinceSelect.innerHTML = options.join(''); } }