Reputation:
The following script link, is linking to a JavaScript file that handle form validation
<script type="text/javascript" src="assets/js/form-validation.js"></script>
And it is included to all the pages using PHP include, the question is; how do I only make it run or even load when there is a form on the page?
I tried this: $('form').load('form-validation.js', function(){ /* callback */ });
But did not work, I also searched and did not find a real answer...
Upvotes: 0
Views: 47
Reputation: 133413
You should use jQuery.getScript(), it load a JavaScript file from the server using a GET HTTP request, then execute it.
You can use .length
property to check form exists or not.
if ($('form').length) {
$.getScript('form-validation.js', function () {
/* callback */
});
}
There is no option to add it to the JS file it self, and make it work
//Place this code at the top of your form-validation.js file
$(document).ready(function () {
if ($('form').length > 0) {
//Do validation
}
});
Upvotes: 2
Reputation: 2551
use jquery to do it :
<script type="text/javascript">
$(document).ready(function(){
if ($('form').length>0) {
$.getScript('form-validation.js', function () {
});
}});
</script>
Upvotes: 0