Я создал сайт разработчиков для проекта, над которым я работаю. Проблема в том, что кажется, что JS работает при загрузке страницы вместо onclick. Он работает правильно после ввода адреса и нажатия кнопки отправки, но предыдущая ошибка все еще остается. Как мне заставить JS запускаться только после нажатия кнопки «Отправить»? Вот код:
/**
* Build and execute request to look up voter info for provided address.
* @param {string} address Address for which to fetch voter info.
* @param {function(Object)} callback Function which takes the
* response object as a parameter.
*/
var userSubmitJS = document.querySelector('#userSubmit');
var userInputJS = document.querySelector('#userInput');
var address;
userSubmitJS.addEventListener('click', function(event) {
event.preventDefault();
address = userInputJS.value;
lookup(address, renderResults);
});
function lookup(address, callback) {
/**
* Election ID for which to fetch voter info.
* @type {number}
*/
var electionId;
/**
* Request object for given parameters.
* @type {gapi.client.HttpRequest}
*/
var req = gapi.client.request({
'path': '/civicinfo/v2/voterinfo',
'params': {
'electionId': electionId,
'address': address
}
});
req.execute(callback);
}
/**
* Render results in the DOM.
* @param {Object} response Response object returned by the API.
* @param {Object} rawResponse Raw response from the API.
**/
function renderResults(response, rawResponse) {
var getResults = document.getElementById('results');
var para = document.createElement("p");
var bold = document.createElement('strong');
if (!response || response.error) {
getResults.appendChild(document.createTextNode(
'Error while trying to fetch polling location.'));
return;
}
var normalizedAddress = response.normalizedInput.line1 + ' ' +
response.normalizedInput.city + ', ' +
response.normalizedInput.state + ' ' +
response.normalizedInput.zip;
if (response.pollingLocations.length > 0) {
var pollingLocation = response.pollingLocations[0].address;
var pollingLocationName = pollingLocation.locationName;
var pollingAddress = pollingLocation.line1 + ' ' +
pollingLocation.city + ', ' +
pollingLocation.state + ' ' +
pollingLocation.zip;
getResults.appendChild(document.createTextNode("The closest polling location near you is: "));
bold.appendChild(document.createTextNode(pollingLocationName + ' '));
getResults.appendChild(bold);
getResults.appendChild(document.createTextNode(pollingAddress));
var getDirections = "Get Directions";
var getDLink = getDirections.link("https://www.google.com/maps/search/" + pollingAddress);
document.getElementById("directions").innerHTML = getDLink;
} else {
getResults.appendChild(document.createTextNode(
'Could not find polling location near ' + normalizedAddress + '. Please try again.'));
}
}
function load() {
gapi.client.setApiKey('XXX');
lookup('', renderResults);
}
<!DOCTYPE html>
<html lang="en">
<head>
<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">
<div class="row">
<div class="col-xl-9 mx-auto">
<h1 class="mb-5">Places to Vote</h1>
<h2 class="mb-5">Find a polling location near you.</h2>
<form>
<div class="form-row">
<div class="col-12 col-md-9 mb-2 mb-md-0">
<input id="userInput" type="text" class="form-control form-control-lg" placeholder="100 Example Ave Austin Texas">
</div>
<div class="col-12 col-md-3">
<button id="userSubmit" type="submit" class="btn btn-block btn-lg btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="container text-center" style="padding-top: 6rem; padding-bottom: 6rem;">
<div class="row">
<div class="col-xl-9 mx-auto" id="results"></div>
<div class="col-md-5 mx-auto" id="directions"></div>
</div>
</div>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
</body>
</html>