我的表单中有一个文本字段,使用此autocomplete script填充。当从自动填充建议中选择一个值时,我希望该字段用建议中显示的值填充(存储在数组arr
中),但我想要一个不同的值与POST请求一起提交提交表单时(存储在数组arr2
中)。
代码:
b.innerHTML += "<input type='hidden' value = '" + arr[i] + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
arr
数组包含应显示的值,而另一个数组arr2
包含应在POST请求期间传递的实际值。
我已经尝试过了:
1)我尝试使用data-value属性来保存实际值,并尝试将其设置为inp.value
,但在这种情况下,当我点击建议时,它不会自动填充。
b.innerHTML += "<input type='hidden' data-value = '" + arr2[i] + "' value = '" + arr[i] + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].data-value;
closeAllLists();
});
a.appendChild(b);
2)我尝试将value属性直接设置为来自arr2
的值,但是在单击建议时,输入字段将填充必须传递的值,而不是必须要传递的值显示。代码如下:
b.innerHTML += "<input type='hidden' value = '" + arr2[i] + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
答案 0 :(得分:2)
我不认为在数据相关时有两个独立的数组是个好主意。我更喜欢考虑对。因此,我使用arr(以及W3CSchools示例中的国家/地区)作为JSON:
var countries = {
"Afghanistan": "af",
"Algeria": "al",
"República Argentina": "ar",
"Belgium": "be",
"Chile": "ch",
};
密钥为arr
,值为arr2
。
Object.keys(countries)
将成为第二个数组。自动完成功能的参数。在通话中:,
autocomplete(document.getElementById("myInput"), Object.keys(countries));
提交(onSubmit
)时,您可以将值分配给隐藏字段,该字段必须具有name
属性
<form [...] onsubmit="prepareData()" >
然后是一个函数
function prepareData() {
document.getElementById("myHiddenField").value = countries[document.getElementById("myInput").value];
}
我将此应用于W3CSchools示例,这是工作示例
function getCountry() {
// I just alert the value, this snippet does not go anywhere
alert( countries[document.getElementById("myInput").value]);
}
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an json (array) of possible autocompleted PAIR OF values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
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]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
/*A JSON containing all the country names in the world:*/
var countries={"Afghanistan":"af","Algeria":"al","Argentina":"ar","Belgium":"be","Chile":"ch"};
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("myInput"), Object.keys(countries));
* {
box-sizing: border-box;
}
body {
font: 16px Arial;
}
.autocomplete {
/*the container must be positioned relative:*/
position: relative;
display: inline-block;
}
input {
border: 1px solid transparent;
background-color: #f1f1f1;
padding: 10px;
font-size: 16px;
}
input[type=text] {
background-color: #f1f1f1;
width: 100%;
}
input[type=submit] {
background-color: DodgerBlue;
color: #fff;
cursor: pointer;
}
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
/*position the autocomplete items to be the same width as the container:*/
top: 100%;
left: 0;
right: 0;
}
.autocomplete-items div {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
/*when hovering an item:*/
background-color: #e9e9e9;
}
.autocomplete-active {
/*when navigating through the items using the arrow keys:*/
background-color: DodgerBlue !important;
color: #ffffff;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Autocomplete</h2>
<p>Start typing:</p>
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php" onsubmit="getCountry()">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input type="submit">
</form>
</body>
</html>
答案 1 :(得分:1)
创建一个新的隐藏字段,该字段将保存必须传递的值并在以后处理它。
c = document.createElement("DIV");
c.innerHTML = "<input type='hidden' value = '" + arr2[i] + "' name = 'newID'>";
this.parentNode.appendChild(c);