/    Sign up×
Community /Pin to ProfileBookmark

Auto Complete twice

How can I make this code work twice on a single page?

“`
<p>
<input list=”suggestionList” id=”answerInput”>
<datalist id=”suggestionList”>
<?php
# https://stackoverflow.com/questions/29882361/show-datalist-labels-but-submit-the-actual-value
include “../scripts/getCities.php”;
$d = json_decode($JSON, true);
foreach ($d as $f){
echo “<option data-value=”” . $f[‘CityID’] .””>” . $f[‘City’] . “, [” . $f[‘ISO_Country’] . “]</option>”;
}
?>
</datalist>
<input type=”text” name=”answer” id=”answerInput-hidden”>
</p>

<script>
document.querySelector(‘input[list]’).addEventListener(‘input’, function(e) {
var input = e.target,
list = input.getAttribute(‘list’),
options = document.querySelectorAll(‘#’ + list + ‘ option’),
hiddenInput = document.getElementById(input.getAttribute(‘id’) + ‘-hidden’),
inputValue = input.value;

hiddenInput.value = inputValue;

for(var i = 0; i < options.length; i++) {
var option = options[i];

if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute(‘data-value’);
break;
}
}
});
</script>

<p>
<input list=”suggestionList2″ id=”answerInput2″>
<datalist id=”suggestionList2″>
<?php
foreach ($d as $f){
echo “<option data-value=”” . $f[‘CityID’] .””>” . $f[‘City’] . “, [” . $f[‘ISO_Country’] . “]</option>”;
}
?>
</datalist>
<input type=”text” name=”answer” id=”answerInput-hidden2″>
</p>

<script>

document.querySelector(“#answerInput2”).addEventListener(‘input’, function(e) {
var input = e.target,
list = input.getAttribute(‘list’),
options = document.querySelectorAll(‘#’ + list + ‘ option’),
hiddenInput = document.getElementById(input.getAttribute(‘id’) + ‘-hidden’),
inputValue = input.value;

hiddenInput.value = inputValue;

for(var i = 0; i < options.length; i++) {
var option = options[i];

if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute(‘data-value’);
break;
}
}
});
</script>
“`

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.8,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...