I'm trying to test some jQuery in this fiddle:
<div id="myDiv"></div>
<input name="Button3" type="button" value="Invoke" onclick="get()">
function get() {
var data = {};
data.foo = "bar";
data.stuff = {
nifty: "stuff"
};
$("#myDiv").text(JSON.stringify(data));
}
The get() function is not being called when I press 'Invoke'. What should occur is the div content should get updated.
3 Answers 3
The reason your fiddle doesn't work is because the settings are wrong. Change onLoad inthe dropdown on the left to no wrap (head) and it will work.
However, as you're using jQuery for your logic, it's best practice to use it to attach events too rather than use the clunky onclick attributes. Try this:
<input name="Button3" type="button" value="Invoke" id="button">
$("#button").click(get);
3 Comments
onLoad on the left, to no wrap (head) and it will work.Jsfiddle evaluates your function on windows.load event:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
function doSomething() {
var data = {};
data.foo = "bar";
data.stuff = {nifty: "stuff"};
("#myDiv").text(JSON.stringify(data));
}
});//]]>
</script>
but the browser needs it on header or before than element that references to it.
you must to chage your code to this:
<div id="myDiv"></div>
<script type="text/javascript" >
function doSomething() {
var data = {};
data.foo = "bar";
data.stuff = {nifty: "stuff"};
$("#myDiv").text(JSON.stringify(data));
}
</script>
<input name="Button3" type="button" value="Invoke" onclick="doSomething()">
BUT,
its recommended to use jquery style event attachment:
<input id="myBTN" name="Button3" type="button" value="Invoke" />
$('#myBTN').click(function(e){
// do something
});
Comments
here you go the updated jiddle
you are calling the function using javascript whereas you have declared the function in you jQuery library.
HTML
<div id="myDiv"></div>
<input name="Button3" type="button" value="Invoke">
Script inside document ready
$('input[type=button]').click(function () {
get();
})
function get() {
var data = {};
data.foo = "bar";
data.stuff = {nifty: "stuff"};
$("#myDiv").text(JSON.stringify(data));
}