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

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

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 😕). HTMLFormElement and HTMLFormControlsCollection interfaces were used to reference <form>, <input>, and <select>. The most important part is declaring a variable outside of fetch(), then defining that variable as the data within fetch() which brings the data within scope for functions, expressions, etc outside of fetch().
Details are commented in example below
// 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>

Related

Adding inputs through for loop

How do I change this code so that when I select an input it adds the text from array based on input id. I have tried to do it myself, but in for loop "i" is always equal to 2, but I want it to be 0, 1 based on which input I select. Please help, I have spent multiple hours with no success.
let basetext = [];
let text1 = document.getElementById("text")
text1.innerHTML = basetext
const thank = [`hi`,
`bye`]
for (i=0; i<thank.length; i++) {
document.getElementById("thank"+i).addEventListener("click", function () {
basetext[i] = thank[i]
text1.innerHTML = basetext.join('')
})
}
<!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" />
<title>Document</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<textarea id="text"></textarea>
<div class="buttons">
<div>
<div>
<input type="radio" name="thank" id="thank0" />
<label for="thank0">first</label>
<input type="radio" name="thank" id="thank1" />
<label for="thank1">second</label>
</div>
<button>Next</button>
</div>
</div>
</body>
<script src="index.js"></script>
</html>
Add a data attribute to each input.
Add a class to a containing element, and then use event delegation to catch events from the child input elements when they're fired. In the handler check to see if the child element that fired the event is a radio input, and then use the data attribute to grab the element from the thank array, and update the textarea content with it.
// Cache the elements
const text = document.querySelector('#text');
const group = document.querySelector('.inputGroup');
// Add one listener to the input group element
group.addEventListener('change', handleChange);
const thank = [`hi`, `bye`];
// Check that clicked input is a radio button,
// grab the id from its dataset, and then use
// that id to add the element from the array to
// the content of the text area
function handleChange(e) {
if (e.target.matches('[type="radio"]')) {
const { id } = e.target.dataset;
text.defaultValue = thank[id];
}
}
<textarea id="text"></textarea>
<div class="buttons">
<div>
<div class="inputGroup">
<label for="0">first
<input
type="radio"
name="thank"
data-id="0"
id="thank0"
/>
</label>
<label for="thank1">second
<input
type="radio"
name="thank"
data-id="1"
id="thank1"
/>
</label>
</div>
<button>Next</button>
</div>
</div>

how to change language for placeholder text?

i cannot change language for my placeholder text. i can only change language for normal button text , head text but i cannot change language for placeholder text. please help to suggest anything i need to add on in my code. thanks
<!DOCTYPE html>
<html>
<head>
<title>Node.js app</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="Style.css" />
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider round">
<span language='myanmar' class="on">MYN</span>
<span language='english' class="off">ENG</span>
</div>
</label>
<div class="form-group">
<input type="text" class="form-control usrplaceholder" placeholder="Username" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control pwplaceholder" name="pw" placeholder="Password" required="required">
</div>
<script>
document.querySelector('#togBtn').addEventListener('input', (event) => {
document.querySelector('.usrplaceholder').textContent = data[event.currentTarget.checked ? 'myanmar' : 'english'].usrplaceholder;
document.querySelector('.pwplaceholder').textContent = data[event.currentTarget.checked ? 'myanmar' : 'english'].pwplaceholder;
});
var data = {
"english": {
"usrplaceholder": "Username",
"pwplaceholder": "Password"
},
"japanese": {
"usrplaceholder": "အသုံးပြုသူအမည်",
"pwplaceholder": "စကားဝှက်",
}
}
</script>
</body>
</html>
There's two problems in your code.
Firstly you're trying to access the myanmar property of the data object when it doesn't exist. The only properties, in the example code at least, as english and japanese.
Secondly, the input elements do not have a textContent property. From the context it looks like you're trying to set the placeholder property instead.
document.querySelector('#togBtn').addEventListener('input', (event) => {
document.querySelector('.usrplaceholder').placeholder = data[event.currentTarget.checked ? 'japanese' : 'english'].usrplaceholder;
document.querySelector('.pwplaceholder').placeholder = data[event.currentTarget.checked ? 'japanese' : 'english'].pwplaceholder;
});
var data = {
"english": {
"usrplaceholder": "Username",
"pwplaceholder": "Password"
},
"japanese": {
"usrplaceholder": "အသုံးပြုသူအမည်",
"pwplaceholder": "စကားဝှက်",
}
}
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider round">
<span language='myanmar' class="on">MYN</span>
<span language='english' class="off">ENG</span>
</div>
</label>
<div class="form-group">
<input type="text" class="form-control usrplaceholder" placeholder="Username" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control pwplaceholder" name="pw" placeholder="Password" required="required">
</div>

Trying to remove JSON.stringfy format from output in Javascript

I trying to get a html-code with javascript to output an array without JSON.stringify. I haven't put in any input validations or anything else, just playing around with arrays and trying to output objects in this array in the html page. I found an example with JSON-stringify which works with my code, but I would like to get the output without JSON-format. For example something like this:
id: 1641231847264,
firstname: asgags
lastname: aasggd
email: sdashga
This code looks like this:
let users = [];
// example {id:1592304983049, Firstname: 'John', Lastname: 'Doe 'Email: john.doe#test.com}
const addUser = (ev) => {
ev.preventDefault(); //to stop the form submitting
let user = {
id: Date.now(),
firstname: document.getElementById('firstname').value,
lastname: document.getElementById('lastname').value,
email: document.getElementById('email').value
}
users.push(user);
document.forms[0].reset(); // to clear the form for the next entries
//document.querySelector('form').reset();
//for display purposes only
console.warn('added', {
users
});
let pre = document.querySelector('#msg pre');
pre.textContent = '\n' + JSON.stringify(users, '\t', 2);
//saving to localStorage
//localStorage.setItem('MyUserList', JSON.stringify(users) );
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addUser);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Putting User Input into JS Objects</title>
<style>
.formBox {
padding: 0.5rem 2rem;
}
</style>
</head>
<body>
<form>
<div class="formBox">
<label for="firstname">Firstname</label>
<input type="text" id="firstname" placeholder="Firstname" />
</div>
<div class="formBox">
<label for="lastname">Lastname</label>
<input type="text" id="lastname" placeholder="Lastname" />
</div>
<div class="formBox">
<label for="email">Email</label>
<input type="text" id="email" placeholder="Email" />
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
</body>
</html>
Have I totally wrong approach for this code or is it just a matter of tweaking the textContent line?
Kind Regards.
It could be a matter of tweaking the assignment:
pre.textContent = users.map(user =>
Object.entries(user).map(([key, value]) =>
`${key}: ${value}`
).join("\n")
).join("\n--------\n");
Loop through the array and properties. Concatenate them all into a string in the format you want, and assign that to the text content.
let users = [];
// example {id:1592304983049, Firstname: 'John', Lastname: 'Doe 'Email: john.doe#test.com}
const addUser = (ev) => {
ev.preventDefault(); //to stop the form submitting
let user = {
id: Date.now(),
firstname: document.getElementById('firstname').value,
lastname: document.getElementById('lastname').value,
email: document.getElementById('email').value
}
users.push(user);
document.forms[0].reset(); // to clear the form for the next entries
//document.querySelector('form').reset();
//for display purposes only
console.warn('added', {
users
});
let pre = document.querySelector('#msg pre');
let msg = users.map(user =>
Object.entries(user).map(([key, value]) => `${key}: ${value}`).join('\n')
).join('\n\n');
pre.textContent = '\n' + msg;
//saving to localStorage
//localStorage.setItem('MyUserList', JSON.stringify(users) );
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addUser);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Putting User Input into JS Objects</title>
<style>
.formBox {
padding: 0.5rem 2rem;
}
</style>
</head>
<body>
<form>
<div class="formBox">
<label for="firstname">Firstname</label>
<input type="text" id="firstname" placeholder="Firstname" />
</div>
<div class="formBox">
<label for="lastname">Lastname</label>
<input type="text" id="lastname" placeholder="Lastname" />
</div>
<div class="formBox">
<label for="email">Email</label>
<input type="text" id="email" placeholder="Email" />
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
</body>
</html>

clear input field when text is entered into another input field

I have a Currency Converter , consisting of two fields and a button. In the first field I type the amount I want to be converted, in the second field I get the result of the conversion.
The question is:
When I type text in the first field, how can I clean up the text from the second field with the conversion result? Using a Javascript / Jquery function?
Thanks in advance.
This is my code:
function convertiLireInEuro() {
var importoInserito = $('#txtLireEuro').val();
importoInserito = importoInserito.replace(/,/g, '.');
var lire = parseFloat(importoInserito)
var euro = lire * 1000 / 1936.27
euro = euro.toFixed(2);
euro = Math.round(euro);
$('#txtConversione').val(euro); }
HTML:
<input type="text" id="txtLireEuro" name="txtLireEuro" style="text-align:right" onkeypress="return onlyNumbers(event);" /> 000 ₤
<input value="Converti in Euro" type="button" id="btnLireEuro" name="btnLireEuro" style="margin-left: 20px" onclick="convertiLireInEuro();highlightAndCopyText();"/>
<input type="text" id="txtConversione" name="txtConversione" style="text-align:right;margin-left:20px" readonly /> €
<span class="Label" style="margin-left:12px">(importo già arrotondato all’intero e incollabile nel campo desiderato)</span>
Here is what you need, I post a coding snippet. I have 2 fields, typing-field and field-to-reset. If you first fill in the field-to-reset with some text and then start typing in typing-field the field-to-reset will reset.
let typing = document.getElementById("typing-field");
let reset = document.getElementById("field-to-reset");
typing.addEventListener("keydown", () => {
reset.value = "";
})
<!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">
<title>Document</title>
</head>
<body>
<div>Typing field:</div>
<input id="typing-field" type="text">
<div>Field to reset:</div>
<input id="field-to-reset" type="text">
</body>
</html>
HTML Code
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
JQuery Code
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#input_box").keydown(function(){
$("#result_box").val("");
})
});
</script>
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
When "Input_box" is getting focus on click the result_box will clear
it's value.
You already have an onkeypress event listener named onlyNumbers. You can simply put $('#txtConversione').val = ""; in that function.

Identify the credit card banner when entering the number

I am developing a system, where the user will have to make the payment via credit card. When he starts typing the first numbers on the card, the flag will be automatically identified and selected. I don't know much about jQuery or JavaScript.
JS
var cartoes = {
visa: /^4[0-9]{12}(?:[0-9]{3})/,
mast: /^5[1-5][0-9]{14}/,
diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}/,
amex: /^3[47][0-9]{13}/,
discover: /^6(?:011|5[0-9]{2})[0-9]{12}/,
hipercard: /^(606282\d{10}(\d{3})?)|(3841\d{15})/,
elo: /^((((636368)|(438935)|(504175)|(451416)|(636297))\d{0,10})|((5067)|(4576)|(4011))\d{0,12})/
};
The problem is that when entering the flag it is not working, that is, he is not selecting the flag as I type the card number. I tried with the cards I have: MasterCard, Amex and Visa. I will put the complete code.
var cartoes = {
visa: /^4[0-9]{12}(?:[0-9]{3})/,
mast: /^5[1-5][0-9]{14}/,
diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}/,
amex: /^3[47][0-9]{13}/,
discover: /^6(?:011|5[0-9]{2})[0-9]{12}/,
hipercard: /^(606282\d{10}(\d{3})?)|(3841\d{15})/,
elo: /^((((636368)|(438935)|(504175)|(451416)|(636297))\d{0,10})|((5067)|(4576)|(4011))\d{0,12})/
};
document.getElementById('num').addEventListener('keyup', testarCC);
var inputs = document.querySelectorAll('.fsResDir input[type="radio"]');
function testarCC(e) {
var nr = this.value;
var tipo;
for (var cartao in cartoes)
if (nr.match(cartoes[cartao])) tipo = cartao;
// alert(tipo);
if (tipo) document.getElementById(tipo).click();
else
for (var i = 0; i < inputs.length; i++) inputs[i].checked = false;
}
<!DOCTYPE html>
<html lang="pt-br">
<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">
<title>Testando a Braspag</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body>
<fieldset class="fsResDir">
<legend>Dados do Cartão </legend>
<input type="radio" name="RadBand" id="visa" />
<label for="visa">
<img src="bandeiras/visa.png" style="width: 90px" />
</label>
<input type="radio" name="RadBand" id="mast" />
<label for="mast">
<img src="bandeiras/mastercard.png" style="width: 90px"/>
</label>
<input type="radio" name="RadBand" id="amex" />
<label for="amex">
<img src="bandeiras/amex.png" style="width: 90px"/>
</label>
<label for="val" class="lab90">Validade:</label>
<input type="text" class="ent20Form" id="val" name="TxtValMes" class="form-control" />/
<input type="text" class="ent40Form" name="TxtValAno" class="form-control" />
<label for="num" class="lab90">Numero:</label>
<input type=text class="ent120Form" id="num" name="TxtNumero" class="form-control" />
</fieldset>
</body>
</html>

Categories

Resources