When I keypress in the input console is continuously showing the error:
Uncaught ReferenceError: showResults is not defined at HTMLInputElement.onkeyup
As you can see in the code, the function is defined. When I remove the AJAX code it starts working. I am unable to find out what the problem is.
let search = $("#livesearch")
function showResults(str) {
if (str.length === 0) {
search.addClass("hide");
} else {
search.removeClass("hide");
}
$.ajax({
url: "/search";
contentType: "application/json",
method: "POST",
data: JSON.stringify({
query: str
}),
success: function(result) {
search.html(result.response);
}
})
}
#addbtn {
font-weight: bold;
background-color: rgb(237, 245, 229);
}
#livesearch {
background-color: #dddd;
position: absolute;
}
.hide {
display: none;
}
a:link,
a:hover,
a:visited,
a:active {
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-xl-7 col-sm-7 col-md-7 ">
<label class="form-label">Add Users</label>
<input id="userinput" type="text" name="users[]" class="form-control" placeholder="Name" onkeyup="showResults(this.value)">
<div id="livesearch" class="p-3 col-12 hide">This</div>
<button id="addbtn" class="form-control mt-3" type="button" onClick="addInput();">Add</button>
<div id="error" class="text-danger p-2"></div>
<div id="formulario" class="d-flex flex-row flex-wrap mt-2"></div>
</div>