Gives an error. I have placed the code just before </body>. Still getting the error.
<form action="" method="get" id="searchform" >
<input name="q" type="text" id="search" size="32" maxlength="128" class="txt">
<input type="button" id="hit" value="Search" onclick="myFunction();return false" class="btn">
</form>
JS,
<script type="text/javascript">
var nexturl = "";
var lastid = "";
var param;
$(document).ready(function () {
function myFunction() {
param = $('#search').val();
alert("I am an alert box!");
if (param != "") {
$("#status").show();
var u = 'https://graph.facebook.com/search/?callback=&limit=100&q=' + param;
getResults(u);
}
}
$("#more").click(function () {
$("#status").show();
$("#more").hide();
pageTracker._trackPageview('/?q=/more');
var u = nexturl;
getResults(u);
});
});
</script>
4 Answers 4
You cannot place myFunction after the onclick. When the onclick is seen there is no definition for myFunction.
Place the JavaScript in <head> tag. Also, move the function outside of ready().
Like this:
<script type="text/javascript">
var nexturl ="";
var lastid ="";
var param;
function myFunction() {
param = $('#search').val();
alert("I am an alert box!");
if (param != "") {
$("#status").show();
var u = 'https://graph.facebook.com/search/?callback=&limit=100&q='+param;
getResults(u);
}
}
$(document).ready(function() {
$("#more").click(function () {
$("#status").show();
$("#more").hide();
pageTracker._trackPageview('/?q=/more');
var u = nexturl;
getResults(u);
});
});
</script>
</head>
<body>
...
3 Comments
myFunction is before or after the onclick attribute. It only matters that it is hidden in the variable scope of the .ready() handler..keep myFunction in script tag directly
i.e
<script>
function myFunction() {
.....
}
</script>
1 Comment
From the jQuery docs:
The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
So your function isn't created until after your onclick is established. Thus it can't find the function. You'll want to move it outside the $(document).ready(function(){}).
5 Comments
$('#data').empty() to the top of the success function, if you don't want the previous results to persist. And if you found my answer helpful, feel free to mark it as your answer.You have to move the function outside the $document.ready here then you will have two options: 1st move it to <head> or 2nd move it right before the closing $document.ready bracket. Use this type of declaration for your function myFunction(){alert("inside my function");};
$(document).ready()construct. It's not needed when you have your code at the bottom.onclick.