Solved

Autofill fields when select box option is selected

Posted on 2013-12-17
8
553 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 43

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 43

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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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 43

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

910 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

20 Experts available now in Live!

Get 1:1 Help Now