Reputation: 10207
This is an excerpt of my javascript file:
$(function() {
if ($('form#search').length > 0) {
setSearchForm();
}
});
function setSearchForm() {
var text=$('form#search input[type=text]');
if (text.val().length != 0) {
text.next('input[type=submit]').removeProp('disabled');
} else {
text.next('input[type=submit]').prop('disabled', true);
}
}
My problem is: All of my subpages use this .js
file but not all subpages do have a search
form.
So on document ready I check for the existence of a search form and then call setSearchForm()
only if a search form exists.
I found that this is the only way to prevent setSearchForm()
from running on every page. Because if there is no search form and the function gets triggered anyway, none of the other functions I have in my js
file will work anymore.
Is there a more elegant solution to this, e.g. by rewriting the function somehow?
I am fairly new to jQuery, so the solution is probably a simple one!
Thanks for any help.
Upvotes: 1
Views: 340
Reputation: 4578
Put the two functions in a separate .js file and import it only on pages that have a search form.
Upvotes: 1