jQuery $(document).ready( function()... called on form submit in Rails app, leading to js error?
Minor issue that I noticed in a Rails app that I use for learning new stuff.
I have some simple jQuery that I use to display the time elapsed since a start_time and an end_time on a form:
$(document).ready(function() {
var initial_start = $('#formatted_start_time').val();
var initial_end = $('#formatted_end_time').val();
$("#duration").text(findDuration(initial_start,initial_end));
})
开发者_JS百科
The findDuration()
function simply returns a string that says "1 hour 12 minutes," or something of the ilk based on the contents of the #formatted_start_time
and #formatted_end_time
fields. This all works as I would expect.
I noticed that the code fires after I submit the form, however, and Web Inspector shows a single js error TypeError: 'undefined' is not an object (evaluating 'startTime.split')
, which just refers to the first line in the findDuration()
function. The 'show' page does not have a #duration
element, so the code shouldn't fire after submitting (or so I thought).
Why is this code running when I click submit and how do I prevent the error?
Edit: The code probably is firing on the 'show' page and not actually when I click submit. The issue seems to be that it is firing on a page with no #duration
element, as if the show page triggers $(document).ready...
for the previous page when it lands on the show page.
A simple way is to check the current page, and if it matches the one you want to run this on, run it.
Alternatively, you could just remove the script from the pages you don't want it to run on, which is a much better way to do it :P
$(document).ready(function() {
if (location.href == 'http://page.you.want/this/to/run.on') {
var initial_start = $('#formatted_start_time').val();
var initial_end = $('#formatted_end_time').val();
$("#duration").text(findDuration(initial_start,initial_end));
}
})
Another alternative to check if the #duration
element exists first;
$(document).ready(function() {
if ($('#duration').length > 0) {
var initial_start = $('#formatted_start_time').val();
var initial_end = $('#formatted_end_time').val();
$("#duration").text(findDuration(initial_start,initial_end));
}
})
精彩评论