0

i'm trying to make a kind of log in system whereas i'd have a string that would be got from user input and i want to check if that input is in a specific array…

What i got so far:

var name = $(".input").value();
var options = ["option_one", "option_two", "three"];
$(".submit").click(function() {

for(i=0; i < options.lenght; i++){
    if(options[i] == name){
        alert("true")
    }else{
        alert("false")
        }
}


});

Can anyone help me out?

EDIT: CodePen

3 Answers 3

2

You can use indexOf like this:

if(options.indexOf(name) != -1){
    alert("valid")
}else{
    alert("false");
}

indexOf will return an index (>=0) from the array where the element is found, -1 otherwise.

Sign up to request clarification or add additional context in comments.

Comments

1

Simplier method - use .includes() function.

http://codepen.io/anon/pen/JEVBgN

var name = $(".input").val();
var options = ["option_one", "option_two", "three"];

console.log(options.includes(name) ? 'valid!' : 'invalid!');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='input' value='three'>

4 Comments

always alerts false :C
@Miguel Check once again. Type three and hit click button.
@Miguel Exactly. The variables were filled immediately when page was loaded. So the value of input was undefined all the time.
@Miguel My pleasure :)
1

Use the javscript Array.prototype.some() function:

var name = $(".input").value();
var options = ["option_one", "option_two", "three"];
if(options.some(el){
  return el == name;
}){
  alert("valid")
}else{
  alert("false");
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.