Solved

Autofill fields when select box option is selected

Posted on 2013-12-17
8
549 Views
Last Modified: 2013-12-17
I have a form that when a contact is selected from a drop down menu, I want to display the phone and email data that we have stored for that user.

I am using PHP/MySQL.

						<li>
							<label for="contact">Company Contact:</label>
							<select name="custContact" class="compContact" required>
								<option value = "">Select Contact...</option>';
								
								//Get Contacts
								$getContacts = mysql_query("SELECT id, name, forename FROM pr_contacts WHERE company = '".$companyNameid."' AND active = '1' ORDER BY forename, name") or die("Cannot pull contacts: " . mysql_error());
								
								if(mysql_num_rows($getContacts) > 0)
									{
									while($contData = mysql_fetch_assoc($getContacts))
										{
										echo '<option value = "'.$contData['id'].'"'; if($contData['id'] == $_POST['custContact']) { echo "Selected = 'SELECTED'";} echo '>'.$contData['forename'] . ' ' . $contData['name'] . '</option>';
										}
									}
									
							echo '</select>&nbsp;&nbsp;<span class="boldblacklinks"><a href="addContact.php?comp='.$companyNameid.'" class="iframetall">Create Contact</span></a>
						</li>
						<li>
						<label for="requireUpdate">Request Update:</label>	
							<table width = "450px" border = "0">
								<tr>
									<td width = "225px"><input type="radio" name="reqUpdate" value = "1" class="reqUpdate" style="width:10px; padding-right:0px;"/>Yes, Update Customer</td>
									<td width = "225px"><input type="radio" name="reqUpdate" class="reqUpdate" value = "0" style="width:10px; padding-right:0px;" />No Update Required</td>
								</tr>
							</table>
						</li>
						<div id="contactInfo" style="display:none;">
							<li>
								<label for="officePhone">Office Phone:</label>
								<input type="text" name="officePhone" id="officePhone" />
							</li>
							<li>
								<label for = "mobilePhone">Mobile Phone:</label>
								<input type="text" name="mobilePhone" id="mobilePhone" />
							</li>
							<li>
								<label for = "email">Email: </label>
								<input type="text" name="emailAddress" id="emailAddress" />
							</li>
						</div>

Open in new window


Here is the code that retrieves the data from the database:

<?php

$programid = "5036";

require_once($_SERVER['DOCUMENT_ROOT']."/includes/verifyaccess.php");
require_once($_SERVER['DOCUMENT_ROOT']."/includes/mainfunctions.php");
require_once($_SERVER['DOCUMENT_ROOT']."/includes/expFunctions.php");

$contactId = $_GET['contactid'];

$sql = mysql_query("SELECT phone1, phone2, email FROM pr_contacts WHERE id = '".$contactId."'") or die("Cannot get contact info: " . mysql_error());

if(mysql_num_rows($sql) > 0)
	{
	while($row = mysql_fetch_assoc($sql))
		{
        //$row_array["id"] = $rs['nameid'];
        //$row_array["label"] = ucwords(strtolower($rs['name'])) . ' ('.$rs['kdaccount'].')';
        //$row_array["value"] = $rs['kdaccount'];
        $row_array["officePhone"]  = ucwords(strtolower($row['phone1']));
		$row_array["mobilePhone"]  = ucwords(strtolower($row['phone2']));
        $row_array["email"] = ucwords(strtolower($row['email']));

        array_push($json, $row_array);        
    }

    header('Content-Type: application/json');
    echo json_encode($json);
?>

Open in new window


I need help with the jQuery portion of this.
0
Comment
Question by:t3chguy
  • 5
  • 3
8 Comments
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39724977
An option to consider here is to store ALL the data you need in the SELECT, and then when it's changed, you're not having to go back to the server to make another request. You would store the info you need in 'data' attributes and then just pull them when the SELECT changes.

Build your <OPTION> tags like this:

<option value="id" data-phone1="phone1" data-phone2="phone2" data-email="email">Persons Name</option>

* Replace the italics with your database values!

Then in jQuery, bind the change() event to the SELECT and update the form fields by grabbing the relevant info using the data() method:

$('select[name="custContact"]').change(function() {
   $('#officePhone').val( $(this).data('phone1') );
   $('#mobilePhone').val( $(this).data('phone2') );
   $('#emailAddress').val( $(this).data('email') );
});

Open in new window

All the data-* attributes you store with each <option> are then available in your jQuery - no round trip to the server..

Hope that makes sense but ask if not :)
0
 
LVL 1

Author Comment

by:t3chguy
ID: 39725043
Great idea.  I've got the code in place, but it's not filling in the fields.  Where did I go wrong?

		echo '<form class="contact_form" action="#" method="post" name="contact_form" id="issueForm">
				<li>
					<label for="contact">Company Contact:</label>
					<select name="custContact" class="compContact" required>
						<option value = "">Select Contact...</option>';
						
						//Get Contacts
						$getContacts = mysql_query("SELECT id, name, forename, phone1, phone2, email FROM pr_contacts WHERE company = '".$companyNameid."' AND active = '1' ORDER BY forename, name") or die("Cannot pull contacts: " . mysql_error());
						
						if(mysql_num_rows($getContacts) > 0)
							{
							while($contData = mysql_fetch_assoc($getContacts))
								{
								echo '<option value = "'.$contData['id'].'"'; if($contData['id'] == $_POST['custContact']) { echo "Selected = 'SELECTED'";} echo ' data-phone1= '.$contData['phone1'] . ' data-phone2= ' . $contData['phone2'] . ' data-email= ' . $contData['email'] . '>'.$contData['forename'] . ' ' . $contData['name'] . '</option>';
								}
							}
							
					echo '</select>&nbsp;&nbsp;<span class="boldblacklinks"><a href="addContact.php?comp='.$companyNameid.'" class="iframetall">Create Contact</span></a>
				</li>
				<li>
				<label for="requireUpdate">Request Update:</label>	
					<table width = "450px" border = "0">
						<tr>
							<td width = "225px"><input type="radio" name="reqUpdate" value = "1" class="reqUpdate" style="width:10px; padding-right:0px;"/>Yes, Update Customer</td>
							<td width = "225px"><input type="radio" name="reqUpdate" class="reqUpdate" value = "0" style="width:10px; padding-right:0px;" />No Update Required</td>
						</tr>
					</table>
				</li>
				<div id="contactInfo" style="display:none;">
					<li>
						<label for="officePhone">Office Phone:</label>
						<input type="text" name="officePhone" id="officePhone" />
					</li>
					<li>
						<label for = "mobilePhone">Mobile Phone:</label>
						<input type="text" name="mobilePhone" id="mobilePhone" />
					</li>
					<li>
						<label for = "email">Email: </label>
						<input type="text" name="emailAddress" id="emailAddress" />
					</li>
				</div>';
?>

<script type='text/javascript'>
$(document).ready(function() 
	{
	$('.reqUpdate').click(function(){
		if($(this).val() == 0) 
			{
			$('#contactInfo').hide();
			} 
			
		else 
			{
			$('#contactInfo').show();
			}
		});
		
	$('select[name="custContact"]').change(function() {
	   $('#officePhone').val( $(this).data('phone1') );
	   $('#mobilePhone').val( $(this).data('phone2') );
	   $('#emailAddress').val( $(this).data('email') );
	});
	

	});
	
</script>

Open in new window

0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39725093
The code that creates your <option> looks a little off (it's quite difficult to tell when concatenating strings like this). Maybe some missing quotes around the data attributes - the easiest way to tell is to view the source once you've loaded your page.

An easier option, which I think makes things much easier to read and debug, is to use the printf() function, instead of trying to concatenate with echo statements. Have a look at this and see if it makes sense:

if(mysql_num_rows($getContacts) > 0) :
	while($contData = mysql_fetch_assoc($getContacts)):
		$option = '<option value="%s" data-phone1="%s" data-phone2="%s" data-email="%s" %s>%s</option>';
		$selected = ($contData['id'] == $_POST['custContact']) ? "Selected = 'SELECTED'" : '';
		printf(
			$option,
			$contData['id'],
			$contData['phone1'],
			$contData['phone2'],
			$contData['email'],
			$selected,
			$contData['forename'] . ' ' . $contData['name']
		);
	endwhile;
endif;

Open in new window

0
 
LVL 1

Author Comment

by:t3chguy
ID: 39725120
The code above did not work either.  here is what the page produces:


<li>
	<label for="contact">Company Contact:</label>
	<select name="custContact" class="custContact" required>
		<option value = "">Select Contact...</option>
		<option value = "60598" data-phone1= "847-451-5000" data-phone2= "312-623-2376" data-email= "alex.shleymovich@hillmech.com">Alex Shleymovich</option>
		<option value = "92563" data-phone1= "847-451-4218 " data-phone2= "773 220 3882" data-email= "anthony.borgnini@hillmech.com">Anthony  Borgnini</option>	
	</select>
</li>

		
	$('.custContact').change(function() {
	   $('.officePhone').val( $(this).data('phone1') );
	   $('.mobilePhone').val( $(this).data('phone2') );
	   $('.emailAddress').val( $(this).data('email') );
	});

Open in new window

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:t3chguy
ID: 39725175
Please note the above code are just the two extracts that we are working with.  I figured it would be cleaner to post that instead of the full code.
0
 
LVL 1

Author Comment

by:t3chguy
ID: 39725178
<div id="contactInfo" style="display:none;">
							<li>
								<label for="officePhone">Office Phone:</label>
								<input type="text" class="officePhone" name="officePhone" id="officePhone" />
							</li>
							<li>
								<label for = "mobilePhone">Mobile Phone:</label>
								<input type="text" class="mobilePhone" name="mobilePhone" id="mobilePhone" />
							</li>
							<li>
								<label for = "email">Email: </label>
								<input type="text" class="emailAddress" name="emailAddress" id="emailAddress" />
							</li>
						</div>

Open in new window

0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39725180
Ahhh. Sorry - my mistake [long day!]

We need to grab the data from the 'selected' option, so your jQuery would look like this:
$('#officePhone').val( $('option:selected', this).data('phone1') );
$('#mobilePhone').val( $('option:selected', this).data('phone2') );
$('#emailAddress').val( $('option:selected', this).data('email') );

Open in new window

You also changed selectors to classes (.) instead of IDs (#)!
0
 
LVL 1

Author Closing Comment

by:t3chguy
ID: 39725200
That'll do it it!  Thank you so much!!
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now