Make jQuery UI autocomplete source dependent on another autocomplete

余生颓废 提交于 2021-01-28 03:48:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!