繁体   English   中英

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

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

我有一个带有 select 字段的表单(在这种情况下是名字),我想要 select 其中一个选项并选择该数据,其他字段应该自动完成。

数据来自 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 和名称已更改(我认为阅读外来词速度较慢——我就是那样笨)。 HTMLFormElementHTMLFormControlsCollection接口用于引用<form><input><select> 最重要的部分是在fetch()之外声明一个变量,然后将该变量定义为fetch()中的数据,这将数据带入 scope 以用于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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM