Megha D S
Megha D S

Reputation: 61

Pass information from div to javascript

I am a newbie and I am trying my hand at javascript for the first time. I have a div that calls a javascript. I have a timezone controller, a show.html which renders the timezone.

<%= render @user.timezones.paginate(page: params[:page]) %>

My partial file for each timzone, _timezone.html,erb :

<tr>
<td><%= timezone.name %></td>
<td><%= timezone.city %></td>
<td><%= (timezone.positive ? '+ ' : '- ') + timezone.hours.to_s + ':' + timezone.minutes.to_s %></td>
<td><div class="time-rect-container" data-positive="<%= timezone.positive %>" data-hours="<%= timezone.hours %>" data-minutes="<%= timezone.minutes%>"></div></td>
<td><%= link_to "edit", edit_timezone_path(timezone) %> </td>
<td><%= link_to "delete", timezone, method: :delete,
                                   data: { confirm: "You sure?" } %> </td>

This partial will be called for every timezone that I have in my database for each user.

And I have the javascript as:

$(document).ready(function () {
setInterval(function () {
 time_div = $('.time-rect-container');
 var dt = new Date();

 var x = time_div.data('hours');
 var y = time_div.data('minutes');
 z = time_div.data('positive') 
 utchours = dt.getUTCHours();
 utcminutes = dt.getUTCMinutes();
 utcseconds = dt.getUTCSeconds();
 if (z == true)
    var time = parseInt( utchours + x + (utcminutes + y) / 60) % 24 + ":" + (utcminutes + y) % 60 + ":" + dt.getUTCSeconds();
 time_div.html(time)
}, 1000);
});

I want the javascript to return different time each time, depending on the hours, minutes of timezone. However for every timezone, the data I am getting in the javascript is the same, i.e, the hours and minutes from the data I am retrieving remainse same for each timezone. Can somebody help fix this?

Upvotes: 1

Views: 100

Answers (1)

Asad Ali
Asad Ali

Reputation: 660

You can use Html Data Attributes for sending info to javascript.

you can generate divs with attribute data-url and pass it timezone-id url. Your divs should look like this.

<div class="time-rect-container" data-url="/timezones/<%= <timezone id> %>/give_time"></div>

Javascript:

$(document).ready(function () {
    setInterval(function () {
     time_div = $('.time-rect-container');
     time_div.load(time_div.data('url'));
}, 1000);

Upvotes: 3

Related Questions