Jump to content

Need some help filling a form based on user selectection in dropdown..


A JM
Go to solution Solved by mac_gyver,

Recommended Posts

I'm looking for some examples or suggestions on the best practices for filling an HTML form based upon a users selection of a dropdown box.

 

I'm seeing a lot of Ajax suggestions but not finding any really good examples as I've not used ajax before it would be great to see some code specific examples.

 

So, essentially a Customer dropdown is fully populated from MySQL when the php page loads and I want the user information (address, city, state, zip, etc.) to be filled in on the form from a MySQL based query using the users selection in the dropdown, seems kind of trivial but I'm finding not so much.

 

I'm pretty sure this is going to involve an onChange() event and some javascript.. just need to be able to put the pieces together.

 

Any ideas and suggestions are welcome.

 

Thanks.

 

AJM,

Link to comment
Share on other sites

Here's some code I use on one of my websites to fill checkboxes based on a what is selected in a select list.

Relevant sections of web page with select:

//javascript
    <script>
        function chkMethods(str)
        {
            if (str == "")
            {
                document.getElementById("mthdboxes").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("mthdboxes").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "method_checks.php?company_valuation_id=" + str, true);
            xmlhttp.send();
        }
    </script>
</head>
<body onload="chkMethods('new');"><!-- to have checkboxes unfilled if a new one -->
//form

  
          <form action="" method="POST">
                <input type="hidden" name="pagesubmitted" value="select_company">
                Choose a Valuation to Work On: <select name="company_id" onchange="chkMethods(this.value)">
                    <option value="new">Add a New Valuation</option>
                    <?php echo $select ?>
                </select><br />Name (or rename) this valuation:<input name="valuationName" type="text">
                <br />
                <div id="mthdboxes">You need to enable javascript for this to work.</div>
                <input type="submit" value="Start or Resume Selected Valuation">
            </form>

and the relevant section of method_checks.php

$company_valuation_id = mysqli_real_escape_string($link, $_GET['compnay_valuation_id']);
if ($company_valuation_id != 'new') {
    $query = "SELECT * FROM company_valuation_methods WHERE company_valuation_id='$company_valuation_id'";
    $result = mysqli_query($link, $query);
    if ($result) {
        while ($method_selected = mysqli_fetch_assoc($result)) {
            $methods[] = $method_selected['method_code'];
        }
    } else {
        $checkboxes = $query . '<br>' . mysqli_error($link);
    }
}
$query = "SELECT * FROM method_code WHERE 1 ORDER BY order_by";
$result = mysqli_query($link, $query);
if ($result) {
    $checkboxes .= "<p> Which method(s) of valuation would you like to use for this report?";
    while ($method = mysqli_fetch_assoc($result)) {
        $checkboxes .= "<br /><input type=\"checkbox\" name=\"method_code[]\" value=\"{$method['method_code']}\"";
        if (in_array($method['method_code'], $methods)) {
            $checkboxes.=" checked=\"checked\" ";
        }
        $checkboxes .=">{$method['method_desc']}";
    }
    $checkboxes .='</p>';
} else {
    $checkboxes = $query . '<br>' . mysqli_error($link);
    //log error here
}
echo $checkboxes;
Link to comment
Share on other sites

your first step will be to code this and get it working without ajax (the core html and server-side code will be needed in either case and will be virtually the same with or w/o ajax) using an onchange event for the select menu that submits the form the select menu is in.

 

then, to add ajax, you will assign an event handler/function to the select menu that when called uses ajax to submit the selected option to the server side code, receives the data back, and populates the form fields.

Edited by mac_gyver
Link to comment
Share on other sites

Thanks for the code daviddannis.

 

method_checks.php, is server side.. correct?

 

So, is Ajax/Javascipt the best and fastest way to accomplish this?

My pleasure. It's only an example. The biggest difference with what you are trying to do is that I send the entire section of the form that will be filled (the checkboxes) from the server using method_checks.php to build it. You will probably just have the section of the form already on the page and just fill in the values. The reason I did it that way it that the number and values of the checkboxes is dynamic and I figured as long as I needed to build that section of the form on the fly I might as well do it once instead of twice.

 

method_checks is server side.

 

Yes, I think that Ajax/JS is the best and fastest way.

 

I think that mac_gyver's suggestion of getting it to work without Ajax first is a good way to go.

Link to comment
Share on other sites

I ran across a piece of code that I believe I understand and can implement but I'm not certain as to how to modify it to return individual fields as oppposed to a recordset? At least that's what it appears the reult is..

 

The query echo's a resultset $packing = $row['packing'];, since I want to fill multiple text boxes I assume they each need a <div> tag but how do I split the resultset to populate my boxes?

 

//getgradepacking.php

<?php
$q=$_GET["q"];
include('includes/connect.php');
mysql_select_db($Db, $link);
$sql="SELECT * FROM grademaster WHERE gradeid = '".$q."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$packing = $row['packing'];
echo $packing;

?>



<div>
    <label>Packing <strong>*</strong></label>
    <textarea id="txtHint" name="txtpacking" id="txtpacking" cols="42" rows="4"></textarea>
</div>



//javascript

<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getgradepacking.php?q="+str,true);
xmlhttp.send();
}
</script>

 

Link to comment
Share on other sites

Thanks, I think the AJAX implementation makes the most sense at the moment - just not sure what the XML object or even if the XML object is returned to be parsed for populating the text boxes...

 

Seems like a basic form implementation to some extent and should be being widely used on the web... maybe others are doing this fully in javascript and not using PHP?

 

Since the project is fully php I've got to come up with some solution to this small problem.. just hoping some someone can shed some additional light on the DIV tag pars of the object returned.

 

AJM,

Link to comment
Share on other sites

I'm close but can't get my <div> tags to update???

<script>
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").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)
    {
    var response = xmlhttp.responseText;
    var update = new Array();
    update = response.split('|$|');
    if(update.length !=0) {
    alert(update[0]);
    alert(update[1]);
        document.getElementById("txtHint2").innerHTML==update[0];
        document.getElementById("txtBlah2").innerHTML==update[1];
        }
    }
  }
xmlhttp.open("GET","../Connections/request.php?q="+str,true);
xmlhttp.send();
}
</script>

</head>

<body>


<form>
<select name="txtHint" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Fredas</option>
<option value="2">Colony</option>
<option value="3">Indiana</option>
</select>
</form>

<div id="txtHint2"><b>Person info will be listed here.</b></div>
<div id="txtBlah2"><b>Person info will be listed here.</b></div>

</body>
</html>
Link to comment
Share on other sites

I found the issue with the source, basically the elements werent being set to the variables correctly..

        document.getElementById("txtHint2").innerHTML=update[0];
        document.getElementById("txtBlah2").innerHTML=update[1];

But like all custom work I ran into another problem.. since the elements require <div> tags to populate the result and the fields that I am attempting to fill with the users selection are <input> I'm not having much luck at making this work since it appears that you can't have a <div> and an <input> together, anyone have any ideas?

 

AJM,

Link to comment
Share on other sites

  • Solution

the example that davidannis gave actually produces the html for the form field he was using, i.e. a select/option menu, then sending the html through ajax to be put into the html of the form.

 

to just put values into type='text' form fields, you would give each form field its own id, then set the value attribute, something like -

document.getElementById("city").value = update[3]; // whatever offset corresponds to the 'city' id form field
Edited by mac_gyver
Link to comment
Share on other sites

I found the issue with the source, basically the elements werent being set to the variables correctly..

        document.getElementById("txtHint2").innerHTML=update[0];
        document.getElementById("txtBlah2").innerHTML=update[1];

But like all custom work I ran into another problem.. since the elements require <div> tags to populate the result and the fields that I am attempting to fill with the users selection are <input> I'm not having much luck at making this work since it appears that you can't have a <div> and an <input> together, anyone have any ideas?

 

AJM,

 

Thanks for the reply mac_gyver.

 

I was able to get past that portion of the code and it made sense after working through it.

 

I'm basically now hung up on the <div> tag and the <input> tag since this is a form for user input should I change the <input> to a <text> instead, do you see any issues with that?

 

AJM,

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.