javascript - 如何在javascript函数中访问表单元素?

标签 javascript jquery django

我正在尝试访问 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/

相关文章:

javascript - 根据confirm()结果创建一个新对象

python - mongoengine 保存时操作错误

python - Django Rest Framework 中的嵌套序列化程序 "Through model"

javascript - 使用 jquery 元素调用 fancybox

javascript - 页面更改时加载的背景图像

javascript - ReactJS:类型数组的状态在重新渲染期间被解构为元素

jquery - 知道为什么快速移动光标时没有注册 mouseleave 事件吗?

javascript - rangeslider.js - 没有在 jquery 中提取正确的数值

javascript - 如何使用 JavaScript/jQuery 替换 URL 的路径名?

python - 覆盖 Django 表单的默认属性