1

I'm trying to access an element in javascript function so as to autocomplete the user search, using autocomplete API.
It is not working as the JS code is not able to access that element. My javascript code:

<script>
$(function() {
  $("#q").autocomplete({
    source: "/api/get_drugs/",
    minLength: 2,
  });
});
</script>

My reference for search.


My Form:

<form id = "myForm" method="GET" action="{% url 'search' %}">
    <input style="width:340px;height:37px;" size="30" type="text" id = 'q' name = 'q' placeholder="Search products or categories"/>
    <input type="submit" value="Search" >
</form>

Here the input target field has id and name- 'q'.

9
  • whats tag with id drugs Commented Sep 14, 2019 at 10:54
  • 1
    Can you explain what the issue is? How does the code fail? Are you getting any error messages in the console? Commented Sep 14, 2019 at 10:55
  • it was a mistake, i have edited it in the question Commented Sep 14, 2019 at 10:55
  • You've changed the selector from '#drugs' to '#q' now. Does that not fix the problem? Commented Sep 14, 2019 at 10:55
  • I;m not getting error, just that it is not being loaded( the javascript function is somehow not working), because it's not able to access that element. Commented Sep 14, 2019 at 10:56

1 Answer 1

1

The bellow code works perfect . Now make sure that the response you are getting from the api is an array .



Or else do one thing , store the response of API in some variable and assign that variable to key Source .
For example :

source : apiResponseVariable //must be array . 

$(function() {
  $("#q").autocomplete({
    source: ["hello" , "how"],
    

  });
});
<!DOCTYPE html>
<html lang="en">
<head>
	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  	<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  	<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>GnG</title>
</head>
<body>
	<form id = "myForm" method="GET" action="{% url 'search' %}">
    <input style="width:340px;height:37px;" size="30" type="text" id='q' name = 'q' placeholder="Search products or categories"/>
    <input type="submit" value="Search" >
</form>

</body>
</html>

You can checkout my running run .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.