简体   繁体   中英

How to fill form fields according to drop down

i have a form with user name, address and email. the list of names is coming from a database, what i need to do is that when i pick the user name, the address and email info fills the other 2 fields (i have another fields, but i only need those filled) I'm using php with mysql database

This may not be optimal - actually I'm not positive it works since I'm not testing this at all, but I'm sure you will figure it out if it doesn't work:

Assuming your form has a name="personInfo", the name drop down has name="personName", and the address is a text input field named "address".

In the personName select tag add

onChange="updateValues()"

Then you will need some javascript that will be something like this:

function updateValue() {
var addresses = new Array();
<?php
//add some php code to populate the java array. Something like
for ($i=0; $i<$numAddresses; $i++) {
    echo 'addresses['.$i.'] ='.$addressFromDB[$i].';';
}
?>
document.personInfo.address.value = addresses[document.personInfo.personName.selectedIndex];   

}

and repeat the same kind of thing for the email

Obviously, you will have to modify this to match your element ID's and such, but this works for me.

Here is your HTML:

<script type="text/javascript">
function grabInfo(str)
{
if (str=="")
  {
  document.getElementById("contentDiv").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
       document.getElementById("contentDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getinfo.php?q="+str,true);
xmlhttp.send();
}
</script>

<select name="users" onchange="grabInfo(this.value)">
    <option value="" selected="selected">Select a person:</option>
    <option value="1">Person A</option>
    <option value="2">Person B</option>
    </select>

    <div id="contentDiv">

    </div>

And backend PHP (getinfo.php):

<?php
$q=$_GET["q"];

//MySQL connection string


$sql="SELECT * FROM <table> WHERE <parameter> = '".$q."'";

$result = mysql_query($sql);


while($row = mysql_fetch_array($result))
  {
  echo '<input type="text" id="address" value="' . $row['address'] . '">';
  echo '<input type="text" id="email" value="' . $row['email'] . '">';
  }
?>

contentDiv will be where the two text boxes are displayed. getinfo.php will be the PHP where the actual manipulation of the database will occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM