在max pleaner评论后编辑的问题

在我正在构建的应用程序中,当用户选择美国作为国家/地区时,我在下面使用此javascript来显示DIV

<script>
  window.onload = function() {
  select_location = document.getElementById('order_country')
  if(select_location[select_location.selectedIndex].value == 'US')
  {
  document.getElementById('country_div').style.display = 'block';
  }
  else
  {
  document.getElementById('country_div').style.display = 'none';
  }
};

</script>


它在页面加载时显示DIV,但是如果用户更改国家/地区,则DIV将不会隐藏。但是,如果我将示例的value == 'US'更改为value == 'CA',则div隐藏,但是如果在视图的Canada中将国家/地区更改为f.country_select,则div仍处于隐藏状态。

所以我的猜测是,当用户在f.country_select中选择国家/地区时,我必须以某种方式修改javascript以进行更新,但是我不确定该怎么做。

这是选择表格

<div class="form-group">
<div class="col-md-5">
    <%= f.label :country %>
    <%= f.country_select :country, { priority_countries: [ "US", "DE", "ES", "PT" ]}, { class: "form-control" }, {:id => "countries"  } %>
</div>


  

html为country_select生成此ID,这就是为什么我在上述id="order_country"中使用javascript的原因

<select class="form-control" name="order[country]" id="order_country">  <option value="US">United States</option>


这是我要显示/隐藏的div

<div class="col-md-5" id="country_div">

 <p>delivery cost</p>

 <p><%= @cart.total_price_usd + @del_cost_usd %></p>

</div>


我自己无法弄清楚。
如果有人可以看看这个并给我建议会很好

提前致谢

最佳答案

每当select的值更改时,都必须执行javascript。您需要在select的change事件上调用一个函数。
使用Jquery可以编写:

$( "#order_country" ).change(function() {
  $('#country_div').toggle();
});

10-04 22:29
查看更多