Skip to content Skip to sidebar Skip to footer

Javascript Onchange Select Value Into Input Field

I have a form in my code that has some input fields and a select field. The select field is populated by a table in a db, which also contains a clients name and e-mail. When the se

Solution 1:

Keep email and name of the client in data-* attributes so that you can retrieve those values on onchange event.

getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string)

Try this:

functionupdateinput(e) {
  var selectedOption = e.options[e.selectedIndex];
  document.getElementById('namecontact').value = selectedOption.getAttribute('data-name');
  document.getElementById('email').value = selectedOption.getAttribute('data-email');

}
<table><tr><td>Company</td><td><selectid="namelist"name="namelist"onchange="updateinput(this)"><option>Select data</option><optiondata-email='abc1@abc.com'data-name='abc1 xyz'value='test'>test1</option><optiondata-email='abc2@abc.com'data-name='abc2 xyz'value='test'>test2</option></select></td></tr><tr><td>Name of contact</td><td><inputrequiredid="namecontact"name="namecontact"type="text"placeholder="Client name"></td></tr><tr><td>E-Mail contactpersoon</td><td><inputrequiredid="email"name="email"type="text"placeholder="E-Mail"></td></tr></table>

Fiddle here

Solution 2:

First, you can store the email value using a data-email attribute in the option element, assuming the name is the text in the option then

<table><tr><td>Company</td><td><selectid="namelist"name="namelist"onchange="updateinput()"><?php$result = mysqli_query($con, "SELECT * FROM clients ORDER BY ID");
    while($row1 = mysqli_fetch_array($result))
    {
        $value = $row1['Value'];
        $name = $row1['Name'];
        $email = $row1['Email'];
        echo"<option data-email='' value='$value'>$name<br>"; } ?></select></td></tr><tr><td>Name of contact</td><td><inputrequiredid="namecontact"name="namecontact"type="text"placeholder="Client name"></td></tr><tr><td>E-Mail contactpersoon</td><td><inputrequiredid="email"name="email"type="text"placeholder="E-Mail"></td></tr></table>

then you can have a change event handler for the select

var namelist = document.getElementById('namelist');
namelist.addEventListener('change', function() {
  var option = namelist.options[namelist.selectedIndex];
  document.getElementById('namecontact').value = option.value;
  document.getElementById('email').value = option.dataset.email;
});

Post a Comment for "Javascript Onchange Select Value Into Input Field"