Rataiczak24 Rataiczak24 - 10 months ago 36
HTML Question

Populate Textfields Depending on Dropdown Selection

I know there are many questions like this one on Stack Overflow, but I am really needing something more related towards what I am doing...so that is why I am posting this question.

I have an HTML form with PHP that pulls data from an MSSQL database in order to populate a dropdown box. I want to be able to populate the contact information text boxes once I select a name from my dropdown box. So far, I have it to where, if I select a specific vendor, the vendor name gets entered automatically into the Name, Email, and Phone Number fields. However, I want to have different attributes entered into the text fields and not the vendor name itself. How could I do this?

The fields from my database with the name, email, and phone number that I want imported are named MR_POC_N, MR_POC_E, and MR_POC_P

Also the "MR_Name" that you see is the field with all names of the vendors FYI. Please help!

Here is my code for the HTML dropdown:

<select name="vendor_dropdown" id="ven" onChange="updateinput();">
<option value="">Choose a Vendor</option>
<?php foreach($users->fetchAll() as $user): ?>
<option><?php echo $user['MR_Name'];?></option>
<?php endforeach; ?>

Here is the update input function I have in JS. I know this is off but looking for some sort of direction as I am not the best in JS:

function updateinput() {

var e = document.getElementById("ven");
var venSelected = e.options[e.selectedIndex].value;


Here is my Contact Info code:

<table align="center">
<td align="right">Name:</td>
<td><input class="textbox" type="text" id="name" name="name"></td>
<td align="right">Email:</td>
<td><input class="textbox" type="email" id="email" name="email"></td>
<td align="right">Phone Number:</td>
<td><input class="textbox" type="tel" id="tel" name="number"></td>

Answer Source

Since the data that you want to populate are already in your '$user' variable, the best way to achieve what you want to do is to use data attributes.

It's pretty simple, you store your data in an attribute on your option, then you can access those value from your js, here is how you could do it :

<select name="vendor_dropdown" id="ven" onChange="updateinput();">
    <option value="">Choose a Vendor</option>
        <?php foreach($users->fetchAll() as $user): ?>
                    data-name="<?php echo $user['MR_POC_N'];?>"
                    data-email="<?php echo $user['MR_POC_E'];?>"
                    data-phone="<?php echo $user['MR_POC_P'];?>"
                <?php echo $user['MR_Name'];?>
        <?php endforeach; ?>

That way all your data wiil be accessible from the js side in the proceding way :

var venSelected = e.options[e.selectedIndex];

document.getElementById("name").value = venSelected.dataset.name

Here is a link talking a little more about data attributes, it never hurts ;)