I have two input fields 1. Name , 2. Telephone. All i want is (1. When I start typing name it must search from database for autocomplete Now when the Name is selected from search query i want Telephone input to be filled automatically on the basis on Name selected. Currently I'm using typeahead.js to autocomplete the Name search.
My HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="typeahed.js"></script>
<style>
h1 {
font-size: 20px;
color: #111;
}
.content {
width: 80%;
margin: 0 auto;
margin-top: 50px;
}
.tt-hint,
.Name {
border: 2px solid #CCCCCC;
border-radius: 8px 8px 8px 8px;
font-size: 24px;
height: 45px;
line-height: 30px;
outline: medium none;
padding: 8px 12px;
width: 400px;
}
.tt-dropdown-menu {
width: 400px;
margin-top: 5px;
padding: 8px 12px;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 8px 8px 8px 8px;
font-size: 18px;
color: #111;
background-color: #F1F1F1;
}
</style>
<script>
$(document).ready(function() {
$('input.Name').typeahead({
name: 'Name',
remote: 'city.php?query=%QUERY'
});
})
</script>
</head>
<body>
<div class="content">
<form>
<h1>Try it yourself</h1>
<input type="text" name="Name" size="30" class="Name" placeholder="Please Enter Name or ZIP code"> </input>
<input type="text" name="Telephone" size="30" class="Telephone" placeholder="Telephone"> </input>
</form>
</div>
</body>
</html>
My PHP Code : //Not putting database connection part (Obviously i have connected it)
<?php
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ($conn,"SELECT Name,Telephone FROM customerdetails WHERE Name LIKE '%{$query}%'");
$array = array();
while ($row = mysqli_fetch_array($sql)) {
$shu[] = array (
'label' => $row['Name'],
'value' => $row['Name'],
);
}
echo json_encode ($shu);
}
?>
The script city.php
have to return values for names and telephone number.
In your example you have twice $row['Name']
.
You have to separate the values that the names are used for the original typeahead search (try template like here) and the telephone number is used when a name is selected. Not used to typeahead but found this solution which looks solid to me to achive what you want.
$('input.Name').typeahead({
name: 'Name',
remote: 'city.php?query=%QUERY',
updater: function(item) {
// try to get telephone number out of "item" and set it to the telephone number field
return item;
}
});
What version of typeahead are you using? https://github.com/twitter/typeahead.js? Maybe you need to include the bloodhound suggestion module...