如何使用一个选择自动填充json表单字段?



我有一个带有选择字段的表单(在本例中是名字),我想选择其中一个选项,并且选中该数据后,其他字段应该自动完成。

数据来自API。

我能够有下拉工作,但每当我选择一个选项的字段没有被填充。

有人能帮我一下吗?这是我的javascript:

document.addEventListener('DOMContentLoaded',() => {
const nomeSelectDrop = document.getElementById('nome');
const sobrenome = document.getElementById('sobrenome');
const email = document.getElementById('email');
const password = document.getElementById('password');
fetch('http://localhost:5000/user')
.then(res => {
return res.json();
})
.then(data => {
let output = "";
data.forEach(users => {
output += `<option value = "${users.firstName}">${users.firstName}</option>`;
})
nomeSelectDrop.innerHTML = output;
})
.catch(err => {
console.log(err);
})
nome.addEventListener('change', (event) => {
sobrenome.innerHTML = event.target.lastName.value;
email.innerHTML = event.target.email.value;
password.innerHTML = event.target.password.value;
})
})
这是我的html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Form Exercise</title>
</head>
<body>
<form class="formulario">
<div class="field">
<label for="nome">Nome:</label>
<select id="nome" name="nome"></select>
</div>
<div class="field">
<label for="sobrenome">Sobrenome:</label>
<input type="text" id="sobrenome" name="sobrenome" placeholder="sobrenome" required>
</div>
<div class="field">
<label for="email">E-Mail:</label>
<input type="email" id="email" name="email" placeholder="e-mail" required>
</div>        
<div class="field">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="password" required>
</div>
<div class="buttons">
<input type="submit" name="atualizar" value="Atualizar">
<input type="submit" name="eliminar" value="Eliminar">
</div>
</form>

<script type="text/javascript" src="app.js"></script>
</body>
</html>

请注意,HTML中的一些#id和名称已被更改(我认为阅读外来词的速度较慢—我这样做很愚蠢😕)。HTMLFormElementHTMLFormControlsCollection接口分别引用<form><input><select>。最重要的部分是在fetch()之外声明一个变量,然后将该变量定义为fetch()中的数据,从而将fetch()之外的函数,表达式等的范围内的数据。

详细信息在下面的示例中被注释

// Reference the <form>
const exc = document.forms.exc;
document.addEventListener('DOMContentLoaded', (e) => {
/*
Collect all <select>,<fieldset>,<input> into a HTMLCollection
*/
let io = exc.elements;
// Declare a variable outside of fetch()
let users;
fetch('https://my.api.mockaroo.com/userlist.json?key=3634fcf0')
.then(res => {
return res.json();
})
.then(data => {
/* IMPORTANT
Define users as JSON data -- now the JSON is in scope within 
this event handler
*/
users = data;
let output = "";
data.forEach(user => {
output += `<option value = "${user.first}">${user.first}</option>`;
});
/*
Use insertAdjacentHTML() instead of innerHTML -- it doesn't destroy 
content it adds to content.
*/
io.first.insertAdjacentHTML('beforeend', output);
})
.catch(err => {});
/*
Bind <form> to the change event
*/
exc.addEventListener('change', (e) => {
// Reference the tag user is interacting with
const sel = e.target;
/*
If the tag the user is interacting with is a <select>...
*/
if (sel.matches('select')) {
// Find the index of selected <option>
let idx = sel.selectedIndex;
/*
users = JSON
Reference index of users with index of selected <option>
*/
io.last.value = users[idx].last;
io.email.value = users[idx].email;
io.password.value = users[idx].password;
}
});
});
html {font: 2ch/1.25 'Segoe UI'}
fieldset {max-width: max-content;}
legend {font-size:1.25rem}
input, select, label {display: inline-block; margin: 2px; font: inherit;}
input:not([type='submit']) {width: 32ch}
[type='submit'] {float: right; cursor: pointer;}
select {width: 33ch}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet">
<title>Form Exercise</title>
</head>
<body>
<form id="exc">
<fieldset class="field">
<legend>User Registration</legend>
<label for="first">First Name: </label><br>
<select id="first" name="first">
<option selected disabled>Select a user</option>
</select><br>
<label for="last">Last Name:</label><br>
<input id="last" name="last" required><br>
<label for="email">E-Mail:</label><br>
<input id="email" name="email" type="email" placeholder="user@mail.com" required><br>
<label for="password">Password:</label><br>
<input id="password" name="password"  type="password" placeholder="Min 8 characters" required>
<menu class="buttons">
<input name="update" type="submit" value='Update'>
<input name="remove" type="submit" value="Remove">
</menu>
</fieldset>
</form>
<script src="app.js"></script>
</body>
</html>

最新更新