I have a rails4 app. Since I\'m not good at js yet I TURNED OFF TURBOLINKS. I have read a bunch of articles, still I couldn\'t figure it out how to organize my javascript files.
$(document).ready
executed once, when the page is loaded. create.js.erb
creates new elements, for which this function is not applied.
Reorganize your code as follows:
js file:
function updatetask($container)
{
$container.find('.updatetask').on('shown.bs.modal', function (e)
{
var deadlineField = $(this).find('.edit-task-deadline');
var deadlineValue = deadlineField.val();
var momentDeadline = moment(deadlineValue).format('MM/DD/YYYY hh:mm A');
deadlineField.val(momentDeadline);
});
}
function new_task_deadline($container)
{
$container.find('.new-task-deadline').datetimepicker({
sideBySide: true,
format: 'MM/DD/YYYY hh:mm A',
stepping: 15,
widgetPositioning: { vertical: 'bottom' }
});
}
$(function () // shortcut for $(document).ready
{
updatetask($(document.body));
new_task_deadline($(document.body));
});
create.js.erb:
$("ul.errors").html("");
<% if @task.errors.any? %>
//modal error messages get inserted via AJAX
$('.alert-danger').show();
$('ul.errors').show();
<% @task.errors.full_messages.each do |message| %>
$("ul.errors").append($("").html("<%= message.html_safe %>"));
<% end %>
<% else %>
//hiding modal on creation and setting values to zero for optional new modal
$('ul.errors').hide();
$('.alert-danger').hide();
$("#newtask").modal('hide');
$(".task_name_company").val('');
$(".contentarea").val('');
$(".new-task-deadline").val('');
// time formatting and datetimepicker for new elements
$task = $('<%= j render @task %>');
updatetask($task);
new_task_deadline($task);
//different div class for different partials + table rows get inserted into view via AJAX
$(".newtaskinsert").prepend($task);
$(".newtaskinsert2").prepend('<%= j render partial: "tasks/task_between", locals: { task: @task } %>');
$("#task_<%= @task.id %>").hide().fadeIn(1000);
<% end %>
For update:
edit_task_submit($(document.body));
function edit_task_submit($container)
{
$container.find('.edit-task-submit').on('click', function (e)
{
e.preventDefault();
var $this = $(this);
var deadlineField = $this.closest('form').find('.edit-task-deadline');
var localMoment = moment(deadlineField.val());
deadlineField.val(localMoment.toISOString());
$this.click();
});
}
update.js.erb:
<% else %>
$('ul.errors').hide();
$('.alert-danger').hide();
$('#updatetask_<%= @task.id %>').modal('hide');
$task = $('<%= j render @task %>');
edit_task_submit($task);
$('#task_<%= @task.id %>').fadeOut(400, function()
{
$(this).remove();
$(".newtaskinsert").prepend($task);
$(".newtaskinsert2").prepend('<%= j render partial: "tasks/task_between", locals: { task: @task } %>');
});
<% end %>