我创建了一个自动提示,以便在键入html字段时显示数据库表的结果,并且我想使用javascript从同一行发布自动建议中的值所在的另一个值。
http://i.imgur.com/ys8mnbV.png
这些建议都有自己的数字,它们不是重复的,而是我需要帮助的地方,我希望这些建议中任何一行的数字都在下面的数字字段中发布。
这是html表单
<div class="floatingBox">
<div class="container-fluid">
<form class="contentForm" form method="POST" form action="index.php">
<div class="control-group">
<label class="control-label">Name:*</label>
<div class="controls">
<input type="text" name="name" class="span4 autosuggest">
<div class="control-group" >
<div class="dropdown">
<ul class="result"></ul></div>
<label class="control-label">Number:*</label>
<div class="controls">
<input type="text" class="span4 number" name="number" placeholder="ex: ######">
</div>
这是Javascript
$(document).ready(function() {
$('.span4.autosuggest').keyup(function() {
var search_term = $(this).attr('value');
$.post('ajax/search.php', {search_term:search_term}, function(data){
$('.result').html(data);
$('.result li') .click(function() {
var result_value = $(this).text();
$('.span4.autosuggest').attr('value', result_value);
$('.result').html('');
});
});
});
});
这是从数据库表中提取信息的PHP
<?
include '../connect.php';
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
$search_term = mysql_real_escape_string($_POST['search_term']);
$query = mysql_query("SELECT * FROM *table* WHERE id = '$userid' AND name LIKE '$search_term%' ");
while(($row = mysql_fetch_assoc($query)) !== false){
echo '<li>', $row['client_name'], '</li>';
}
}
?>
答案 0 :(得分:0)
使用PHP发出JSON而不是HTML。然后使用Javascript填充字段。 PHP(假设包含该编号的行称为“客户编号”)
<?
include '../connect.php';
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
$search_term = mysql_real_escape_string($_POST['search_term']);
$query = mysql_query("SELECT * FROM *table* WHERE id = '$userid' AND name LIKE '$search_term%' ");
$results = array();
while(($row = mysql_fetch_assoc($query)) !== false) {
$results[] = array('client_name' => $row['client_name'], 'client_number' => $row['client_number']);
}
header("Content-Type: application/json");
echo json_encode($results);
}
?>
的Javascript
$(document).ready(function() {
$('.span4.autosuggest').keyup(function() {
var search_term = $(this).attr('value');
$.post('ajax/search.php', {search_term:search_term}, function(data){
for(var k in data) {
$('.result').append("<li data-number='"+data[k].client_number+"'>"+data[k].client_name+"</li>");
}
$('.result li') .click(function() {
$('.span4.autosuggest').val($(this).text());
$('.span4.number').val($(this).data("number"));
$('.result').html('');
});
});
});
});