我正在尝试访问 javascript 函数中的元素,以便使用 autocomplete 自动完成用户搜索。 API。
它不起作用,因为 JS 代码无法访问该元素。
我的 JavaScript 代码:
<script>
$(function() {
$("#q").autocomplete({
source: "/api/get_drugs/",
minLength: 2,
});
});
</script>
我的引用search 。
<小时/> 我的表格:<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>
此处输入目标字段具有 id 和名称 - 'q'。
最佳答案
下面的代码完美运行。现在确保您从 api 获得的响应是一个数组。
或者做一件事,将 API 的响应存储在某个变量中,并将该变量分配给键 Source 。
例如:
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>
你可以查看我的运行记录。
关于javascript - 如何在javascript函数中访问表单元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57934761/