Reputation: 77
I am trying to make an array with names, then to iterate them using a for of loop and then to check the iteration using a if else statement. My code is below, but it did not work, I saw no result. I tried with for in, the same bad result. In Html file I have a paraghraph with demo id and a button with function for iterate and checking array
function availableName() {
const check = document.getElementById('userID');
const takenNames=['manuel','remus','manuel-remus','tomi','mirel'];
const reservedNames=['cristina','angela','rusanda','costantin'];
const givenNames=[...takenNames, ...reservedNames];
for (givenName of givenNames) {
if (givenName === check) {
sayMessage=givenName +"Not available!";
}
else {
sayMessage= givenName +"Available";
}
}
document.getElementById("available").innerHTML= sayMessage;
};
Upvotes: 1
Views: 58
Reputation: 32145
First of all you need to get the value of the input
using .value
as stated in comments.
Then to check its existence in the array
you can use one of Array
's built-in methods, such as includes()
or indexOf()
.
This is how should be your code:
function availableName() {
const check = document.getElementById('userID').value;
const takenNames = ['manuel', 'remus', 'manuel-remus', 'tomi', 'mirel'];
const reservedNames = ['cristina', 'angela', 'rusanda', 'costantin'];
const givenNames = [...takenNames, ...reservedNames];
if (givenNames.indexOf(check) > 0) {
sayMessage = check + " Not available!";
} else {
sayMessage = check + " Available";
}
document.getElementById("available").innerHTML = sayMessage;
};
Demo:
This is a Demo:
function availableName() {
//const check = document.getElementById('userID').value;
const check = "cristina";
const takenNames = ['manuel', 'remus', 'manuel-remus', 'tomi', 'mirel'];
const reservedNames = ['cristina', 'angela', 'rusanda', 'costantin'];
const givenNames = [...takenNames, ...reservedNames];
if (givenNames.indexOf(check) > 0) {
sayMessage = check + " Not available!";
} else {
sayMessage = check + " Available";
}
document.getElementById("available").innerHTML = sayMessage;
};
availableName();
<div id="available"></div>
Upvotes: 1
Reputation: 61
Why not use the function isInArray?
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
function availableName() {
const check = document.getElementById('userID');
const takenNames=['manuel','remus','manuel-remus','tomi','mirel'];
const reservedNames=['cristina','angela','rusanda','costantin'];
const givenNames=[...takenNames, ...reservedNames];
for (givenName of givenNames) {
if (isInArray(check, givenNames)) {
sayMessage=givenName +"Not available!";
}
else {
sayMessage= givenName +"Available";
}
}
document.getElementById("available").innerHTML= sayMessage;
};
Upvotes: 1