【发布时间】:2020-08-17 20:31:30
【问题描述】:
我创建了一个应用,它使用多个 Google 地图 API 来返回起始地址和目的地地址字段之间的距离和行程时间。当我最初创建它时,我通过从变量addresses 值中获取值进行测试,该值是我从公司的数据库查询中提取的 15 个服务地址位置的数组。在我的 for 循环中,我动态填充了起始地址 (startaddress[i]) 和目标地址 (destaddress[i+1])。这是我最初测试时它的工作原理的屏幕截图。我掩盖了实际地址,但它确实在这里按预期工作。
在对此进行测试后,我创建了一个表单,该表单采用用户在输入字段(位于页面顶部)中输入的地址或邮政编码值,我想填充#destaddress(目标地址或第二个地址字段)用于标记为“目标地址”的每个输入字段。用户可以输入这些值中的任何一个,我想用用户输入值填充我的 for 循环中的每个 destaddress。我尝试在 getDistance 函数之前将其填充到 for 循环中,在那里我设置了 destInput.value = patientAddress.value,但是当我输入值并使用 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);
如果我在函数setPatientAddress 内部分配patientAddress 的值后控制台记录destInput 的值,我可以看到该值在for 循环内显示了15 次,但值destInput 的输入字段未填充。不过我不太清楚为什么。
【问题讨论】:
标签: javascript forms event-handling user-input