Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 575
  • Last Modified:

Autofill fields when select box option is selected

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
t3chguy
Asked:
t3chguy
  • 5
  • 3
1 Solution
 
Chris StanyonCommented:
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
 
t3chguyAuthor Commented:
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
 
Chris StanyonCommented:
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
t3chguyAuthor Commented:
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
 
t3chguyAuthor Commented:
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
 
t3chguyAuthor Commented:
<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
 
Chris StanyonCommented:
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
 
t3chguyAuthor Commented:
That'll do it it!  Thank you so much!!
0

Featured Post

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.

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