HTML:
<table>
<tr>
<td align="center">
<label for="InputBox1"><b>~</b><font color="red">*</font>: </label>
</td>
</tr>
<tr>
<td align="center">
<div id="1"></div>
<p id="InputBox1Error"></p>
<input id="input" name="InputBox1" style="width: 250px;" onblur="InputBox1()">
<div id="suggest"></div>
</td>
</tr>
</table>
javascript(内联):
<script type="text/javascript">
$(document).ready(function(){
$("#input").keyup(function(){
$("#suggest").html("");
var input = $("#input").val();
input = $.trim(input);
if(input){
$.ajax({
url: "ajax.php",
data: "input="+input,
success: function(msg){
$("#suggest").html(msg);
}
});
}
});
});
</script>
javascript源文件:
$(document).ready(function(){
$("#input").keyup(function(){
$("#suggest").html("");
var input = $("#input").val();
input=$.trim(input);
if(input){
$.ajax({
type:'POST',
url: "PathToPHPfile",
data:"input="+input,
success: function(msg){
$("#suggest").html(msg);
$("#suggest ul li").mouseover(function(){
$("#suggest ul li").removeClass("hover");
$(this).addClass("hover");
})
$("#suggest ul li").click(function(){
var value=$(this).html();
$("#input").val(value);
$("#suggest ul").remove();
if(input.value != ''){
document.getElementById("input").style.backgroundColor = "#BFFFBF";
}
});
}
});
}
});
});
$(document).ready(function(){
$("#suggest").autocomplete({ // myevent_name is the id of the textbox on which we are applying auto complete process
source:'<?php echo get_bloginfo("template_url");?>/PHPfile',
minLength:1
});
});
PHP:
<?php
$dbh=mysql_connect ("~", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");
$input = $_REQUEST['input'];
$input = mysql_real_escape_string(trim($input));
$sql = "SELECT * FROM ~ WHERE ~ LIKE '%".$input."%'";
$data = mysql_query($sql);
$arrcnt = -1;
$dataArray = array();
while ($temp = mysql_fetch_assoc($data))
{
foreach($temp as $key=>$val) {
$temp[$key] = stripslashes($val);
$arrcnt++;
}
$dataArray[$arrcnt] = $temp;
}
$list = "<ul class='unorganised' style='width:100;height:auto;'>";
foreach($dataArray as $val) {
$list .= "<li class='list'>".$val['~']."</li>";
}
$list .= "</ul>";
echo $list;
?>
我的主要问题:这适用于一个输入框(id =“input”)。我正在尝试将其应用于同一HTML页面上的10个输入框,以便每个输入框都具有来自mysql数据库中同一个表的自动完成功能。自动完成功能不会对输入框(id =“input2”)等执行(我将变量名称更改为其他输入框ID)。换句话说,如何将此逻辑应用于同一HTML页面上的多个输入框?请帮忙。
答案 0 :(得分:0)
你的问题是你的jQuery只针对一个框的ID:
<div id="suggest"></div>
而是考虑:
<div>
<input id="input" name="InputBox1" style="width: 250px;" onblur="InputBox1()">
<div class="suggest"></div>
</div>
然后:(你的内联javascript)
<script type="text/javascript">
$(document).ready(function(){
$("input").keyup(function(){
var suggestionBox = $(this).next('.suggest');
suggestionBox.html("");
var inputValue = $.trim($(this).val());
if(input){
$.ajax({
url: "ajax.php",
data: "input="+inputValue,
success: function(msg) {
suggestionBox.html(msg);
}
});
}
});
});
</script>