如何解决在表单提交的for循环内填充输入字段值
我创建了一个使用多个Google Maps API的应用程序,以返回起始地址和目标地址字段之间的距离和行程时间。最初创建此文件时,我通过从变量addresses
值中获取值进行了测试,该值是从公司的数据库查询中提取的15个服务地址位置的数组。在我的for循环内,我动态填充了起始地址(startaddress [i])和目标地址(destaddress [i + 1])。这是我最初测试时的工作原理的屏幕截图。我掩盖了实际的地址,但是它确实按预期在这里工作。
对此进行测试之后,我创建了一个表单,该表单采用用户输入到输入字段(在页面顶部)的地址或邮政编码值,我想在其中填充#destaddress
(目标标记为“目标地址”的每个输入字段的地址或第二地址字段)。用户可以输入这些值中的任何一个,我想用用户输入的值填充for循环中的每个destaddress
。我尝试在getDistance
函数(设置destInput.value = patientAddress.value
)之前的for循环中填充此函数,但是当我输入值并使用setPatientAddress函数提交表单时,什么也没发生。
我的问题是,如何通过此表单从我的html表单#patientaddress
的顶部输入内容中填入目标地址?
HTML:
<!DOCTYPE html>
<head>
<title>Service Center - Google Maps Distance Search</title>
<link rel="stylesheet" type="css" href="main.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<div class="container-lg" style="margin-top:20px;">
<form id="form" method="post" accept-charset="utf-8">
<div class="card">
<div class="card-body">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Destination</span>
</div>
<input class="form-control" type="text" placeholder="Zip or Full Address" id="patientaddress">
</div>
<button class="btn btn-outline-primary mt-2" type="submit" id="submit">Submit</button>
</div>
</div>
</form>
<p id="log"></p>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&key=[GoogleMapsAPIkey]"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
JavaScript:
let startInput,destInput;
// Set headers
const headers = {
'QB-Realm-Hostname': 'xxxxxxxx.quickbase.com','Authorization': 'QB-USER-TOKEN xxxxxxxxxxxxxxxxxxxxxxxxxxxxx','Content-Type': 'application/json'
}
// Call QB table and pull data from column facID 6,address 8
const body = {
"from": "xxxxxxxx","select": [6,8],"options": {
"skip": 0,"top": 0
}
}
function generateHTML() {
// Create xml request class
const xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST','https://api.quickbase.com/v1/records/query',true);
// Extract keys from headers
for (const key in headers) {
xmlHttp.setRequestHeader(key,headers[key]);
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === XMLHttpRequest.DONE) {
const jsonObject = JSON.parse(xmlHttp.responseText);
const facId = jsonObject.data.map(e => e["6"].value);
const addresses = jsonObject.data.map(e => e["8"].value);
// Grab container div entry point in html
const container = document.querySelector(".container-lg");
// const patientAddress = document.querySelector("#patientaddress");
const form = document.querySelector("#form");
const patientAddress = document.querySelector("#patientaddress");
// Create html elements dynamically based on length of addresses array
for (let i = 0; i < addresses.length; i++) {
let div = document.createElement("div");
div.classList.add("card","card-body","mb-3");
div.innerHTML = `<div class="mx-auto" style="width: 800px; margin-top: 25px;">
<h5 class="card-title">Service Center: ${facId[i]}</h5>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Starting Address</span>
</div>
<input class="form-control" readonly type="text" placeholder="Start Address" id="startaddress${i}">
</div>
<br />
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Destination</span>
</div>
<input class="form-control" type="text" placeholder="Zip or Full Address" id="destaddress${i}">
</div>
<hr />
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Distance <span id="distance${i}"></span></h5>
</div>
</div>
<br />
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Trip Time <span id="time${i}"></span></h5>
</div>
</div>`;
container.appendChild(div);
// Dynamically set and number input fields
startInput = document.querySelector(`#startaddress${[i]}`);
startInput.value = addresses[i];
destInput = document.querySelector(`#destaddress${[i]}`);
// destInput.value = patientAddress.value;
function setPatientAddress(e) {
destInput.value = patientAddress.value;
console.log(destInput.value);
e.preventDefault();
}
// destInput.value = destinationAddresses[0];
function getDistance() {
// Create Google Maps distance matrix class
const distanceService = new google.maps.DistanceMatrixService();
// Add matrix settings
distanceService.getDistanceMatrix({
// Origins and destinations must be called inside of the for loop
origins: [startInput.value],destinations: [destInput.value],travelMode: "DRIVING",unitSystem: google.maps.UnitSystem.IMPERIAL,durationInTraffic: true,avoidHighways: false,avoidTolls: false
},// Set catch,try
function(response,status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
console.log('Error:',status);
} else {
// console.log(response);
destInput.value = patientAddress.value;
document.getElementById(`distance${[i]}`).innerHTML = `${response.rows[0].elements[0].distance.text}`;
document.getElementById(`time${[i]}`).innerHTML = `${response.rows[0].elements[0].duration.text}`;
}
});
}
// Register Focus out Listener on Input Fields so we calculate distance and Time
startInput.addEventListener("focusout",getDistance);
destInput.addEventListener("focusout",getDistance);
form.addEventListener('submit',setPatientAddress);
// getDistance();
// end for loop
}
}
};
// Send body request object to Quick Base via RESTful API
xmlHttp.send(JSON.stringify(body));
}
// Call The generateHTML Function when the page is ready
google.maps.event.addDomListener(window,'load',generateHTML);
如果我在函数destInput
内将patientAddress
的值赋值后控制台setPatientAddress
的值登录,我可以看到该值在for中显示了15次。循环,但是destInput
的输入字段的值未填充。我不确定为什么。
解决方法
我删除了
google.maps.event.addDomListener(window,'load',generateHTML);
在我的JavaScript代码的最后。然后,我添加了一个名为inputVal
的全局变量,并为其指定了空字符串的值。
在我添加的generateHTML
函数之后,在代码的末尾
const form = document.querySelector("#form");
const patientAddressValue = document.querySelector("#patientaddress");
const destiInput = document.querySelector(".destInput");
form.addEventListener("submit",(e) => {
e.preventDefault()
inputVal = patientAddressValue.value;
console.log(inputVal);
// Call The generateHTML function only after the user enters a value
generateHTML();
});
此功能允许我将inputVal
设置为用户输入的值,并将其分配给patientAddressValue
。value的值。在删除触发generateHTML
函数的侦听器之后,我可以在此新函数中调用它。
此刻,我只能捕获字符串的第一部分,因此,如果我添加地址,例如910 Diamond St,圣地亚哥,CA 92109,我只会通过910,所以我仍在处理此问题除非有人也可以帮助我弄清楚这部分。但是,我可以输入zip来触发我想要的功能。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。