I have a simple HTML. I am using the JQuery for AJAX purpose. Now, I want to put my javascript function in a separate javascript file. What is the syntax for this? For example, currently my script section in the HTML is something like this:
<script> <script type='text/javascript' src='scripts/scripts.js'></script> <script type='text/javascript' src='scripts/jquery.js'></script> <script type = 'text/javascript' language='javascript'> $(document).ready(function() { $('#SubmitForm').click(Submit()); }); </script>
But I want to put the function
function() { $('#SubmitForm').click(Submit()); })
in the file scripts.js. Can I use assign a name to that function and refer to it?
EDit: I still have a bit of problem here: I changed the code to
<script type = 'text/javascript' language='javascript'> $(document).ready(function() { $('#SubmitForm').click(submitMe); }); </script>
and in a separate js file, I have the following code:
var submitMe = function(){ alert('clicked23!'); //$('#Testing').html('news'); };
Here’s the body section:
<body> welcome <form id='SubmitForm' action='/showcontent' method='POST'> <input type='file' name='vsprojFiles' /> <br/> <input type='submit' id='SubmitButton'/> </form> <div id='Testing'> hi </div> </body>
Yet, it is still not working, anything I miss?
Move the scripts.js
scripttag down beneath the jQueryscripttag and then just move the whole of that inline script block into scripts.js. As jQuery will already have been instantiated by the time scripts.js loads, the Javascript will just execute inline in the same way that it does at the moment.Also on a separate note, you need to change
to
You don’t want the parentheses because you are not executing the function at this point, merely telling the click event handler that this is the name of the function that you want to execute when the event fires.
And as another tip, you can replace
$(document).ready(with$(ie:Both
$anddocument.readycan be included anywhere on the page (or in external files) and as long as jQuery.js is in scope, they will fire at the same time (once the DOM has loaded) – you don’t need to worry about it being the last bit of code to fire. This is why you can move the whole thing to scripts.js rather than needing to assign a name to the function and refer to it from the inline script.For the record, if you do wish to refer to the function by name, simply define it as a variable:
Like I say though, this is possibly somewhat overkill in your situation, you might as well just move the whole thing to scripts.js (unless of course there’s more to it than you’ve mentioned in your question.
Edit (to deal with edit to question): Looks like you are dealing with the wrong event handler. You are trying to assign a function to the click event handler for the form, whereas you really want to be assigning it to the handler for the submit button. You should therefore be using the selector ‘#SubmitButton’ ie: