Reputation: 550
Please tell me why if you add a value to the search, then the span is not filled? If you leave only the if, then everything works. I can't understand what the problem might be, since this is a common condition, if the code is found, then it displays the country in the span.
Without the else:
var phones = [{
"country": "UA",
"code": "+380"
},
{
"country": "RU",
"code": "+7"
},
{
"country": "MD",
"code": "+373"
}
];
$(".phone").keyup(function() {
var val = $(this).val();
phones.find(function(phones) {
if (phones.code == val) {
$("#county").text(phones.country);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="county"></span>
<input type="text" class="phone">
With else:
var phones = [{
"country": "UA",
"code": "+380"
},
{
"country": "RU",
"code": "+7"
},
{
"country": "MD",
"code": "+373"
}
];
$(".phone").keyup(function() {
var val = $(this).val();
phones.find(function(phones) {
if (phones.code == val) {
$("#county").text(phones.country);
} else {
$("#county").text("no");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="county"></span>
<input type="text" class="phone">
Upvotes: 0
Views: 96
Reputation: 2874
Because .find is looping through all your objects. If you search for lets say +7, it will show no then RU then no again, so it overwrites the value while without the else it gets in once and stays like that without replacing.
The solution here is to finish with your find first, and then do the if.
I would do something like this:
var phones = [{
"country": "UA",
"code": "+380"
},
{
"country": "RU",
"code": "+7"
},
{
"country": "MD",
"code": "+373"
}
];
$(".phone").keyup(function () {
var val = $(this).val();
var phoneObj = phones.find(x => x.code == val);
if (phoneObj == undefined) {
$("#county").text("no");
}
else {
$("#county").text(phoneObj.country);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="county"></span>
<input type="text" class="phone">
Upvotes: 2
Reputation: 50291
That is because the next value is not same as the input code, so the else loop is executed & shows no
.
Explanation: The array method iterates all the object. So when the input matches it shows the country. But when the next object is under iteration it does not match with the input value. Hence the previous text is over written.
The input is +7
and matches with the code and showing the country. But immediately after that +7
is compared with next object and the code does not match. So else loop is executed.
When using only if
nothing happens when the code and input value does not match.
Upvotes: 1