I am sure this question is posted before, but didn’t find it in javascript/jquery.
So I have two inputs, first one is a city, and second one is a part of that specific city that we chose in first input:
$(function() {
var city = ["option1", "option2", "option3", "option4"];
$("#city").autocomplete({
source: city
});
var addressforoption1 = ["a1", "a2", "a3", "a4"];
var addressforoption2 = ["b1", "b2", "b3", "b4"];
var addressforoption3 = ["c1", "c2", "c3", "c4"];
var addressforoption4 = ["d1", "d2", "d3", "d4"];
var answer = document.querySelector('#city').value;//tried changing this to innerText or innerHTML still the same
if (answer = "option1") {
address = addressforoption1
}
if (answer = "option2") {
address = addressforoption2
}
if (answer = "option3") {
address = addressforoption3
}
if (answer = "option4") {
address = addressforoption4
}
$("#location").autocomplete({
source: address
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<label for="city">➡ City<span style="color:red;">*</span></label>
<input type="text" required name="city" id="city" placeholder="Enter your city name here">
<hr>
<label for="location">➡ Location<span style="color:red;">*</span></label>
<input type="text" required name="location" id="location" placeholder="City location">
Problem: First autocomplete works with charm, and you can pick any city you want, exactly like it should. But second autocomplete is always last one – option 4
2
Answers
You must use double equal sign operator (
==
) for comparison and then change your code to something like thisI added
select
andchange
methods to your code.select
–You can use the
select
property in autocomplete to pass along the selected value, here I just call the functionsetAddressValue
that basically does the same as what you did before.change
–select only handles when the user actually selects the value from the autocomplete-list. if I manually enter
option1
and then try, nothing is going to happen. So therefore, I added thechange
method which basically checks whenever a user is leaving the input field.Notes:
if(answer = "option1")
will assignoption1
toanswer
. Essentially what you did was to check ifanswer
was a truthy value, and a string is a truthy value. So therefore all if-cases were true., And that’s why it always showed the last one, it passed through them all. You need to do==
or===
for comparisons.Don’t use
var
. Useconst
for variables that you wont reassign, andlet
for variables you want to re-assign a value to.