I have a form with a select field (for this case is the first name), I want to select one of the options and with that data selected, the other fiels should be auto completed.
The data is comming from an API.
I'm able to have the dropdown working but whenever I select one option the fields aren't being populated.
Can someone help me, please?
This is my 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;
})
})
This is my 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 >
<div >
<label for="nome">Nome:</label>
<select id="nome" name="nome"></select>
</div>
<div >
<label for="sobrenome">Sobrenome:</label>
<input type="text" id="sobrenome" name="sobrenome" placeholder="sobrenome" required>
</div>
<div >
<label for="email">E-Mail:</label>
<input type="email" id="email" name="email" placeholder="e-mail" required>
</div>
<div >
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="password" required>
</div>
<div >
<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>
CodePudding user response:
Be aware that some of the #ids and names in HTML has been changed (I think slower reading foreign words -- I'm dumb that way