views:

93

answers:

8

I'm new to Javascript and jQuery. I want to click a button and have a js function executed. (For this example, it's just an alert, but it's actually an ajax function.)

The first alert appears, but after I click the button, I never see the second ("did it") alert. It looks like javascript doesn't think the doIt() function is defined when the button is clicked.

Here's the relevant code:

$(document).ready(function()
{ 
    alert('ready');

    function doIt() {
        alert('did it');
    };
}
)

<body>
    <input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
+1  A: 

What you need to do is bind a "click" event to it using jquery like this.

jQuery(document).ready(function($) {

    $('#my_button').click(function() {

        alert('i was clicked');

    });
});  

<input type="button" id="my_button" value="Go" />

Here is a live jsfiddle demo for you: http://jsfiddle.net/8A5PR/

Here is the manual page for you: http://api.jquery.com/click/

Paul Dragoonis
No, the onClick is correct.
Konerak
@Konerak I think you miss the point, this allows you to extract the onclick event management from the tag, and put it in the javascript with the function, thus you manage your code (behavior) separate from your markup while the execution functionality remains the same - to handle the click event of the element on your page.
Mark Schultheiss
@Mark - I don't think @Konerak missed the point at all. This answer states that you *"need to bind a click event to us using jquery"*. That is not correct. Binding events with jQuery is an option, but you don't need to do it.
patrick dw
+9  A: 

It's because that function isn't in a global context, which is where your onclick="" is looking for it. You need to move it outside your document.ready (so it's not scoped exclusively to that closure), or (a better approach IMO) bind it inside the document.ready, here's what I mean by each:


Binding it inside (remove your onclick="" for this):

$(document).ready(function() { 
  alert('ready');
  $("input[name='Go']").click(doIt);
  function doIt() {
    alert('did it');
  }
});

or the anonymous version (again remove your onclick=""):

$(document).ready(function() { 
  alert('ready');
  $("input[name='Go']").click(function() {
    alert('did it');
  });
});

Or move it outside (keep your onclick=""):

$(document).ready(function() { 
  alert('ready');
});
function doIt() {
  alert('did it');
}
Nick Craver
or keep it inside, but declare it as a global function (keep your onclick)
Konerak
I actually do BOTH of these, depending upon circumstances. For instance, I use .ascx files with included Javascript at times, and when I do so, placing the function inside limits the scope of the function, but other times I want a global function that I call from multiple includes - in that case, I move the function outside the scope. So, both of these options have uses.
Mark Schultheiss
+2  A: 

You define doIt in your document.ready as a function statement.

Either you should use a function expression or declare the function out of the ready function.

$(document).ready(function()
{ 
    alert('ready');

    doIt = function() { //now has global scope.
        alert('did it');
    };
}
)

<body>
    <input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>

(yes, the onClick is not really the jQuery way of doing it and probably should be replaced by a click handler defined in the ready function, but it works and is allowed.

Konerak
are you sure this works? `doIt` is still declared in local scope.
fearofawhackplanet
If I would have put `var doIt`, you would have been right. Omitting the `var` declares a global variable.
Konerak
+1 then for teaching me something new then. Is that a jQuery feature or applicable to general JavaScript?
fearofawhackplanet
@fearofawhackplanet :general JavaScript
Mark Schultheiss
@fearofawhackplanet see this for a more in depth treatment of the subject: http://articles.sitepoint.com/article/oriented-programming-1/3
Mark Schultheiss
A: 

What you are doing right now is simply putting a function doIt() inside a (for all intents and purposes) window.onload event. This function will never get called outside of the document.ready unless you bind it to an element because it's stuck inside the scope of document.ready.

You need to move your function outside of the document.ready so it can be called by outside events.

Just a little link for reference: http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3

lighthazard
From the documentation: "With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads." http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
Mark Schultheiss
Oh, I made a mistake then, I guess it's BEFORE window.onload.
lighthazard
Not really a mistake just understanding :) another way to state this is "when the DOM is ready", so that page might not be 100% rendered, but the DOM (Document Object Model) is ready.
Mark Schultheiss
A: 

Try this...

$(document).ready(function() {


    alert('ready');


        $("#Go").submit(function(event) {
           alert('did it');
        });

 });

<input name="Go" id="Go" type="button" value="Go" />
Amit
Might be i am late to post answer coz answers are already posted..No worries :)
Amit
+2  A: 

Javascript has two kinds of scope, global, and function level. If you declare doIt inside a function, it will not be visible outside the function. There are a few ways to fix it

//just declare the function outside the ready function
$(function() {
});
function doIt() { alert('did it'); }

//decare a variable outside the function
var doIt;
$(function() {
  doIt = function() { alert('did it'); }
});

// if you dont use var, variables are global
$(function() {
  doIt = function() { alert('did it'); }
})
Matt Briggs
+1  A: 
$(document).ready(function() 
{ 
});

is an event handler for document.ready, the functions inside that handler are within that scope.

A better method is to insert a handler for your click event inside, then call that function there.

$(document).ready(function() 
{  
    alert('ready'); 

  $('body input').click(function(){
    doIt();
  });
   function doIt() { 
        alert('did it'); 
    }; 
});

This ALSO has the side effect of removing code from your markup (a good thing) in that you can remove that onclick from your input tag.

Mark Schultheiss
A: 

Yes, as mentioned by others you really need to move the function outside of the jquery ready declaration. Also please note that javascript is case sensitive, hence you should use onClick rather than onclick. Regards

Muleskinner
Actually, it is not javascript. It is an HTML attribute. `onclick` will work just fine, as will `oNcLiCk`.
patrick dw
please check ur cAPS lOCL - JUST jokin' ur absolutely right of course
Muleskinner