I am trying to create a simple User Information form. In my form i have a select element with four options inside it. The options have four data attributes with some information for the users. Below my select i have four input types that will represent one of the data attribute that i have on my select. What I would like to happen is when i select each of the user to get the data attributes and fill in the input elements. Anyone know how can I achieve that? I would like it in plain JS. I have tried using onchange event but no luck. Can someone provide me with the JS code? I will add many users so if someone can help me with the code using (this) instead of selecting users with id i would appreciate it.
Thanks.
HTML:
<form id="usersInfo" action="#" method="post" onsubmit="return false">
<label>User Information</label>
<select id="firstSelect" onchange="usersFunction()">
<option value="10" data-name="Name One" data-surname="Surname One" data-email="Email One" data-country="Country One">User One</option>
<option value="20" data-name="Name Two" data-surname="Surname Two" data-email="Email Two" data-country="Country Two">User Two</option>
<option value="30" data-name="Name Three" data-surname="Surname Three" data-email="Email Three" data-country="Country Three">User Three</option>
<option value="40" data-name="Name Four" data-surname="Surname Four" data-email="Email Four" data-country="Country Four">User Four</option>
</select>
<input type="text" id="userName" placeholder="User Name">
<input type="text" id="userSurname" placeholder="User Surname">
<input type="text" id="userEmail" placeholder="User Email">
<input type="text" id="userCountry" placeholder="User Country">
</form>
Javascript
function usersFunction() {
var x = document.querySelector("#firstSelect");
var dataName = x.getAttribute("data-name");
var dataSurname = x.getAttribute("data-surname");
var dataEmail = x.getAttribute("data-email");
var dataCountry = x.getAttribute("data-country");
var userName = document.querySelector("#userName");
var userSurname = document.querySelector("#userSurname");
var userEmail = document.querySelector("#userEmail");
var userCountry = document.querySelector("#userCountry");
userName.value = dataName;
userSurname.value = dataSurname;
userEmail.value = dataEmail;
userCountry.value = dataCountry;
}