• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 730
  • Last Modified:

Show results in textfield dependent on a selection in a dropdown menu

Hi

I've got a table in a database (tableA) and a PHP page which contains one form (form1).

tableA has two fields called subject and bookTitle.

The first field in the form1 is a dynamic dropdown list that contains values from the field  bookTitle in tableA.

The second field in the form1 is a textfield and needs to automatically be filled with the corresponding subject from tableA dependent on what the user has picked in the dynamic dropdown above.

I've got all of my connections set up correctly and I've got the text for the dynamic dropdown list OK.  I'm just a bit stuck on the automatic insertion of the text into the textfield after the user has made their selection within the dropdown list.

Any ideas?

Thanks in advance
N
0
nelliott
Asked:
nelliott
1 Solution
 
Marcus BointonCommented:
This is mainly a Javascript problem. You need to generate the mapping from booktitle to subject using PHP, then give it to Javascript so that it can put it into the subject field. You'd call a JavaScript function from an onChange handler that looks up the book and puts the corresponding subject in the subject field.
0
 
nelliottAuthor Commented:
Ok.  The theory's good, but being neither a PHP or Javascript expert, how do I do this in practice?
0
 
nowaydown1Commented:
Good day:

The good news is that the solution to this isn't as complicated as describing the problem was.  =)  Thus far, you've done the hard part.  You are getting the values from the database and displaying them in your dynamic dropdown box.  This is a good thing.  In order to pull off the effect you want, what you are really going to need is some fancy javascript.  If your into the techie explanations, what you'll need to do is set the value of your dropdown box (there is a value parameter -- see the code example below), to the subject.  You'll need to modify your database query in order retrieve this information as well.  Then, you write a javascript function (This is where the fancy javascript comes in) to actually make the change in the textfield you have.   That makes my head spin, so take a look at the following.  Hopefully it will clarify.

<?php

// This is my php script that actual writes the html code for my page that is displayed
// to my users--


echo "
<html>
<head>
<script language=\"javascript\">
function getTitle() {
      document.form1.bookSubject.value=document.form1.bookTitle.value;
}
</script>
</head>
<body>

<form method=\"POST\" name=\"form1\" action=\"submit.php\">
<p>Book Subject: <input type=\"text\" name=\"bookSubject\" size=\"20\"></p>
<p>Book Title: <select size=\"1\" name=\"bookTitle\" onchange=\"getTitle()\">";


$query="SELECT * FROM tableA";
if($hResult=mysql_query($query)) {
    while($hFetch=mysql_fetch_array($hResult)) {
           $bookTitle=$hFetch[bookTitle];
           $bookSubject=$hFetch[subject];

           echo "<option value=\".$bookSubject."\">".$bookTitle."</option>";
    }
}

echo "
</select>
</form>
</body>
</html>";

-----------------------------------------------------------------------------------------------------

It's hardly a work of art, but it should clarify the idea for you.  Please be aware that it's 3 AM, so there may be errors.  I didn't test the code.  The javascript function (Which is the real missing piece of the puzzle here) should work properly for you however.  

Please let me know if there is anything else that I can do to assist you.  Always happy to answer any other questions you may have about this solution!  Have a wonderful day!  
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Boris AranovichSenior Software EngineerCommented:
I am not a Javascript expert, but the idea is this:

Generate a JS array, that will contain an entry for each text entry, indexed by the Id of the book.
now, the Dropdown should be something like
<option value="[Id]">[Title]</option>

and the <select onChange="updateText(this.value)">
Now, I am not sure if "this.value" is supposed to return the currently selected value, or something like "this.options[this.selectedIndex]" (or something like that, not sure, just making it up now) :)

and the function will do something like

// this is the array
var theMappingArray = new array(...................);


function updateText(theValue)
{
   oBox = document.getElementById('myTextArea');
   oBox.innerText = theMappingArray[theValue];
}


anyhow, this is the idea, consider this only as guideline, as an algorithm, and not as to code...
I don't really have now time to check for the exact code and/or write it, but if nobody will answer till evening, i'll try to help maybe
0
 
nelliottAuthor Commented:
nowaydown1 - this is really close.  2 problems though:

1.  The form used is actually an Insert into Database Form so I need to keep the value of the option tag set to that of $bookTitle.  I thought I could get around this by using a hidden input tag, but I got myself into a right muddle.

2.  When the script populates the textfield it only brings up the first word of the text string.  For instance if the value of bookSubject was 'Physical Education' then it only inserts 'Physical' into the textfield.

Any ideas?

I've upped the points, as I forgot to mention what the form was for.

Thanks in advance
N
0
 
nelliottAuthor Commented:
Sorted out point two by adding quotes:

      $bookTitle=$hFetch["bookTitle"];
      $bookSubject=$hFetch["subject"];
      echo "<option value='$bookTitle'>$bookTitle</option>";

Still need to get the $bookSubject into the javascript.

N
0
 
nowaydown1Commented:
nelliot:

The second issue was a simple typo on my part.  On the other hand, the fact that we also now need to update the value that's listed in this textbox adds some more complexities to this problem.  It still can be done, but it will require the slight modification of our database table and a good bit of tweaking to our existing code sample. Basically, our existing table isn't very efficient.  It doesn't catalog the data in a such a way that it plays nice with multiple values or other tables in the database that may be relational to this one.  

Generally, what your going to want to do here is add a field at the beginning of your database table that is called bookID.  I'm hoping that your using phpMyAdmin to manage your database, otherwse I can look up the mysql sytax to accomplish this addition for you.  So if you are using this, go ahead and add a new field to the table at the start of the table.  Name the field bookID.  Give it type INT, and set the Length/Values field to 11.  In the extra dropdown box, select auto_incremement.  Now click on the Primary radio button.  Then click Save.  

By allowing the table to auto_incremement itself, we open up a whole world of automation and possibilities that are far beyond the scope of this message.  If you are unfamiliar with how auto_incremement works and it's application with PHP, I would highly suggest taking a thumb through the mysql.com manual sometime--definately worth a read.  Regardless, back to the issue at hand here.  

I reworked the code from the previous example, fixing all the errors and actually testing this time.  Everything works fine from what I can tell.  You'll see that there are several changes to this version from the previous.  I've tried to document the code the best I could to give you an idea of what is happening along the way.  This will definately require a solid understanding of arrays.  Also, by doing it this way, we were able to add in some of the missing features, like setting the textbox to a value when the page loads.  =)

Here is the code:

<?php

// This is just my own personal database connection info--
include("cnx.php");                              

// This function is called both after the data has been updated
// and when the user first logs onto the script.  
function showUpdatePage() {

$numberOfBooks=0;                  // The number of books found in the database--


// You'll notice that I moved this from it's previous location further down the
// line in the script.  The reason for this is because I need access to these variables
// while I'm writing my javascript functions below.  Also this allows us to populate our
// textbox once the page loads--

$query="SELECT * FROM tableA";
if($hResult=mysql_query($query)) {
    while($hFetch=mysql_fetch_array($hResult)) {
           $numberOfBooks++;
               $bookID[$numberOfBooks]=$hFetch[bookID];                        // The new column we added
               $bookTitle[$numberOfBooks]=$hFetch[bookTitle];            // The book title
           $bookSubject[$numberOfBooks]=$hFetch[subject];            // The book subject
    }
}


// So you'll notice here that I added a new javascript function called
// bookIDToDescription.  This function takes a numeric bookID (like the one
// we just added into our database table for example), and retrieves the
// book subject information based on it's ID.  In this way, we could also
// add access to any other variables we might add to our table in the future.  
// It's much more extensible then our previous example.  

echo "
<html>
<head>
<script language=\"javascript\">
function getTitle() {
     document.form1.bookSubject.value=bookIDToDescription(document.form1.bookTitle.value);
}
function bookIDToDescription(bookID) {
      var bookDescription=new Array();";
      echo "\n";
      for($numOfBooks=1;$numOfBooks <= $numberOfBooks;$numOfBooks++) {
            echo "      bookDescription[".$numOfBooks."]=\"".$bookSubject[$numOfBooks]."\"";
            echo "\n";
      }
      echo "
      return bookDescription[bookID];
}
</script>
</head>
<body>

<form method=\"POST\" name=\"form1\" action=\"".$PHP_SELF."\">
<p>Book Subject: <input type=\"text\" name=\"bookSubject\" size=\"20\" value=\"".$bookSubject[1]."\"></p>
<p>Book Title: <select size=\"1\" name=\"bookTitle\" onchange=\"getTitle()\">";

for($displayOptions=1;$displayOptions <= $numberOfBooks;$displayOptions++) {
      echo "<option value=\"".$bookID[$displayOptions]."\">".$bookTitle[$displayOptions]."</option>";
}


// I also added this submit button named update, which is why I have the
// if(!isset($_POST['update'])) clause below--
echo "
</select>
<input type=\"submit\" name=\"update\" value=\"Update\">
</form>
</body>
</html>";
}

// The the script really begins here now instead--
if(!isset($_POST['update'])) {                  // If the hasn't pushed the submit button--
      showUpdatePage();                              // Then they probably havent seen the form yet, so show it to them                              
} else {      
      // Otherwise, they did push it, so update the information in the database--
            $bookSubject=$_POST['bookSubject'];            // Get the values from the form--
      $bookTitle=$_POST['bookTitle'];
      
      // Notice that we're updating bookID here now instead.  I changed the bookTitle dropdown box to hold
      // the numeric bookID instead of the actual subject.  Then our little javascript function does the
      // conversion for us.
      $sqlUpdateTheDatabase="UPDATE tableA SET subject='$bookSubject' WHERE bookID='$bookTitle'";
      if($hResult=mysql_query($sqlUpdateTheDatabase)) {
            // If everything went smoothly--
            echo "<center><b>Your information was updated successfully.</b></center><br><br>";   // Tell the user everything went good--
            showUpdatePage();                                                                                                       // Then show the user the page again--
      } else {
            die("<center><b>An error occurred: ".mysql_error()."</b></center><br><br>");            // An error occured--
      }
}

?>

---------------------------------------------------------------------------------------------------------------

As I said previously, this code -should- work fine out of the box.  I did test it.  Please let me know if you come across any additional issues.  Additionally, if you would like to see a runtime copy of it, you may by visiting a temporary upload of this script at:

http://client.webdmp.net/sportscomplex/includes/test.php

I will leave it up for 3 days for your review if need be.  Also, I wasn't 100% clear on what you meant by the first step you outlined, about an insert into a database form.  I just assumed you wanted the data updated.  If you actually wanted an INSERT instead of an UPDATE, this should be an easy change.  

I will have to say is probably the most complicated simple script I've done yet.  Always a pleasure to work on a unique challenge though.  
Hope this works well for you.  Your free to use this code as you please.  Enjoy!  --Noway

0
 
nowaydown1Commented:
Additionally, here is a dump from my phpMyAdmin install of the table structure:

CREATE TABLE `tableA` (
  `bookID` int(11) NOT NULL auto_increment,
  `bookTitle` text NOT NULL,
  `subject` text NOT NULL,
  PRIMARY KEY  (`bookID`)
) TYPE=MyISAM AUTO_INCREMENT;

Just for your reference.
0
 
nelliottAuthor Commented:
Fantastic - much more complicated than I first imagined it was going to be, but going through the code bit by bit has helped me tremendously - especially with such well commetned code.

I really appreciate this.

Points increased to 500 as such a good solution.

Many Thanks
N
0
 
nowaydown1Commented:
Not a problem.  =)  Thanks very much for your kindness.  Glad that I could help!  
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now