简体   繁体   中英

Rails ERB select_tag, update default value with javascript

I currently have a select_tag that selects the current day and looks like this (The last value specifies which one is selected):

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

The problem that I've run into is that the server uses UTC and as a result the date may not be correct for the client, depending on his or her location. I found some Javascript that will return the correct day for the client.

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

How do I get the ERB tag to use the client current day by plugging in this value to replace Time.now.wday as the default value for the select_tag.

I've considered something like this

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

but the ID tags for the select_tag are dynamically generated, so I'm not sure how to plug it in.

Any help would be appreciated!

Final solution, thanks to 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>

You can pass in a static 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') %>

Or even a class if you want:

<%= 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') %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM