我有一个简单的 Web 表单,它使用使用 javascript 自动完成数组的输入字段。
我遇到的问题是我希望 javascript 自动完成数组获取 php 客户的名字和姓氏,这将在 Web 表单输入文本字段中输入时显示。单击自动完成列表中的名称后,我就可以提交表单。输入文本字段使用客户 ID。
我怎样才能让它发挥作用?
<小时/>javascript:
<script type="text/javascript">
function autocomplete(inp, arr) {
var currentFocus;
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
for (i = 0; i < arr.length; i++) {
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
b = document.createElement("DIV");
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
}
}
});
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
currentFocus++;
addActive(x);
} else if (e.keyCode == 38) { //up
currentFocus--;
addActive(x);
} else if (e.keyCode == 13) {
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
if (!x) return false;
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
var customers = ["<?php echo strtoupper($CustomerSet['customer_first'] .' '. $CustomerSet['customer_last']);?>"];
autocomplete(document.getElementById("myInput"), customers);
</script>
<小时/>
php:
<?php
foreach ( $this->fetchCustomers[2] as $CustomerSet ) :
echo '<option value="'. $CustomerSet['id'] .'" ';
if ( $_POST['customerID'] == $CustomerSet['id'] ) :
echo ' SELECTED ';
endif;
echo '>'. strtoupper( $CustomerSet['customer_first'] ) .' '. strtoupper( $CustomerSet['customer_last'] ) .' - '. $CustomerSet['id'] .'</option>';
endforeach;
?>
<小时/>
html:
<input type="text" name="customerID" id="myInput" placeholder="Select Customer" value="">
最佳答案
我建议你查一下“ajax”是什么,查一些教程。
关于javascript - 在 javascript 自动完成中获取 php 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54424031/