问题
The problem is in the title, I don't know how to make an autocomplete widget dependent on the other. In my example, I have 2 columns in my database:
- firstName
- lastName
And some rows:
Dupont Francois
Dupont Oliver
Lapeche Jean
If I enter Dupont
in the first autocomplete input, I want the second autocomplete to suggest Oliver
and Francois
, not Jean
!
This is my code HTML :
<form action="../../controler/add/addUserDevice.php" onsubmit="return verifUserDevice(this)" method="post">
<table>
<tr>
<td>Last Name</td>
<td><input type="text" class="userLastName" name="userLastName"/></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" class="userFirstName" name="userFirstName" /</td>
</tr>
<tr>
<td colspan="3"><input class="buttonIndex" type="submit" value="Create" /></td>
</tr>
</table>
And my PHP code for the seconde autocomplete
<?php
include('../../model/connexion_sql.php');
if ((include_once '../../model/connexion_sql.php') === FALSE)
exit('erreur include');
if (isset($_GET['term'])) {
$connection = new Connection;
$connection->connection();
$conn = $connection->getConnection();
$requete = $conn->prepare('SELECT userFirstName FROM user WHERE userFirstName LIKE :term');
$requete->execute(array('term' => $_GET['term'] . '%'));
$array = array();
while ($donnee = $requete->fetch()) {
$array[] = $donnee['userFirstName'];
}
echo json_encode($array);
}
?>
and my JavaScript:
$(function(){
$(".userFirstName").autocomplete({
source: '../../model/autocomplete/userFirstName.php',
minLength: 1
});
});
回答1:
$(function() {
$(".userFirstName").autocomplete({
autoFocus:true,
source: function( request, response ) {
$.ajax({
url: '../../model/autocomplete/userFirstName.php?userLastName=' + $("#userLastName").val() + "&term=" + request.term,
dataType: "json",
success: function( data ) {
response(data);
}
});
},
minLength: 1
});
});
Your ajax request will look like that.
Add id="userLastName"
to your userLastName input.
Add this in your PHP script
if($_GET['userLastName']) {
$userLastName = $_GET['userLastName'];
} else $userLastName = null;
then change
SELECT userFirstName FROM user
WHERE userFirstName LIKE :term
BY
SELECT userFirstName FROM user
WHERE userFirstName LIKE :term
AND (userLastName = :userLastName OR :userLastName is null)
来源:https://stackoverflow.com/questions/30324821/make-jquery-ui-autocomplete-source-dependent-on-another-autocomplete