Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: (function) is not defined at HTMLButtonElement.onclick

I have a search form where I'm trying to have it output the results at the bottom of the page without reloading.

<form action='' method='post'>
<div id="search-form">      
<input type="text" name="search" class="search-field" id="search" value="" />
<div class="submit-container">
<button type="button" value="" class="submit" id="searchbutton" onclick="searchoutput()" /></button>
            </div>
  </form>
  <br><br>
  <p>Type First Name</p>

I want the search results to show below when the button is clicked, using Ajax call to another script. I keep getting an error: "Uncaught ReferenceError: searchoutput is not defined at HTMLButtonElement.onclick

Here is my javascript (using jquery):

$( document ).ready(function() {
function searchoutput() {
     if($(".search-field").val().length > 5) { //only shows results when more than 5 characters have been entered
        var search = $(".search-field").val();
        var update = $(".result");
        var goal = 0;
        $.get("query-include.php" , {search: search, goal: goal})
        .done(function( data ) {
          update.empty();
          update.append(data);
          $(this).remove();
                                });
                                             };
                         } 
  $( ".search-field" ).keydown(function() {
      var update =$(".results");
      update.empty();
                                       });
                             });

I have checked other posts and spent a long time trying to get the solution on my own. The odd thing is if I add an event listener for "keyup" in order to run the same function searchoutput as the user types:

var searchfield = document.getElementById("search");
searchfield.addEventListener("keyup", searchoutput);

Then I don't get the ReferenceError and the script runs fine.. I only get the function issue on button click.

like image 513
Daniel C Avatar asked Jan 07 '17 23:01

Daniel C


1 Answers

It's a scoping issue - searchOutput is defined within the scope of the $(document).ready() function. What you could try is to declare a var for searchOutput before that code, then assign it to the function like this:

var searchOutput;
$( document ).ready(function() {
  searchOutput = function () {
   if($(".search-field").val().length > 5) {
   //etc.
like image 85
hackerrdave Avatar answered Nov 20 '22 02:11

hackerrdave