如何使用 select 自动填充 json 的表单域?

How to auto populate form fields with json using one select?

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

数据来自 API。

我可以让下拉菜单正常工作,但每当我 select 一个选项时,字段都不会被填充。

有人可以帮我吗?

这是我的 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 和名称已更改(我认为阅读外来词速度较慢——我就是那样笨)。 HTMLFormElement and HTMLFormControlsCollection 接口用于引用 <form><input><select>。最重要的部分是在 fetch() 之外声明一个变量,然后将该变量定义为 fetch() 内的数据,这将数据置于 fetch() 之外的函数、表达式等范围内。 =20=]

详情见下方示例

// 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>