Rails ERB select_tag,用javascript更新默认值

时间:2017-08-23 01:29:18

标签: javascript ruby-on-rails html-select

我目前有一个select_tag选择当天,看起来像这样(最后一个值指定选择哪一个):

<%= select_tag(:day, options_for_select([['Sunday', 0], ['Monday', 1],
['Tuesday', 2], ['Wednesday', 3], ['Thursday', 4], ['Friday', 5],
['Saturday', 6]], Time.now.wday)) %>

我遇到的问题是服务器使用UTC,因此客户端的日期可能不正确,具体取决于他或她的位置。我发现了一些Javascript会为客户返回正确的日期。

<script>
  function getDay(){
    var d = new Date();
    var n = d.getDay();
  }
</script>

如何通过插入此值将 Time.now.wday 替换为select_tag的默认值,让ERB标记在当天使用客户端。

我考虑过这样的事情

document.getElementById("id_of_select_tag").selectedIndex = n;

但是select_tag的ID标签是动态生成的,所以我不知道如何插入它。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

最终解决方案,感谢Babar

<%= select_tag(:day, options_for_select([['Sunday', 0], ['Monday', 1], ['Tuesday', 2], ['Wednesday', 3], ['Thursday', 4], ['Friday', 5], ['Saturday', 6]], 0), id: 'static-id-of-select-tag') %>

<script>
function myFunction() {
var d = new Date();
var n = ndgetDay();

document.getElementById("static-id-of-select-tag").selectedIndex = n;
}
myFunction()
</script>

答案 1 :(得分:0)

您可以传入静态ID:

<%= select_tag(:day, options_for_select([['Sunday', 0], ['Monday', 1],
['Tuesday', 2], ['Wednesday', 3], ['Thursday', 4], ['Friday', 5],
['Saturday', 6]], Time.now.wday), id: 'static-id-of-select-tag') %>

如果你愿意,甚至可以上课:

<%= select_tag(:day, options_for_select([['Sunday', 0], ['Monday', 1],
['Tuesday', 2], ['Wednesday', 3], ['Thursday', 4], ['Friday', 5],
['Saturday', 6]], Time.now.wday), class: 'static-class-for-js') %>