mrpinkman
mrpinkman

Reputation: 211

How to get just one value from array in javascript

i'm learning javascript and i've tried something but i can't figure out how to make it work, here's my code so far:

HTML

<p>Busca tu auto:</p>
<input type="text" id="search"><span> </span><button>Submit</button>
<p class="hide h1" style="color:green">Your car is available.</p>
<p class="hide h2" style="color:red">Your car is not available.</p>

JS

$(document).ready(function(){
    var cars = ['mercedes','nissan','ferrari','bmw','fiat','toyota','renault','peugeot','kia'];
    $('.hide').hide();
    $('button').click(function(){
        if($('#search').val() == cars[x]){
            $('.h1').show();
            $('.h2').hide();
        } else {
            $('.h2').show();
            $('.h1').hide();
        };
    });
});

What I want to do is that when you click the button check if the car is available (it's not real). For example, it you type "mazda" and click the button, h2 will show, but if you type "ferrari" and click the button, h1 will show.

I'm approaching to the solution with my code above or not?

NOTE: if you change the "x" in cars[x] for a number it works, but just with one car.

Upvotes: 4

Views: 487

Answers (3)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Since this question is also tagged jQuery:

From the jQuery docs:

jQuery.inArray( value, array [, fromIndex ] )

Which would be:

$.inArray(('#search').val(), cars) !== -1

This also has the advantage of working in IE8 and below, something that Array.prototype.indexOf does not.

Upvotes: 1

Joeytje50
Joeytje50

Reputation: 19112

You can search through arrays by using the Array.indexOf method:

if (cars.indexOf($('#search').val()) !== -1) {
    //your code here
}

The Array.indexOf method will return -1 when no exact matches are found (this includes lowercase/uppercase differences), and otherwise it will return the index of the match in the array. That means that if the entered value is in your array, it will return something other than -1, so the if-statement will return true.

To make this case-insensitive, use the following:

if (cars.indexOf($('#search').val().toLowerCase()) !== -1) {
    //available
} else {
    //unavailable
}

that converts the input to lowercase first, and checks afterwards. For this to work, all values stored in the array would need to be in all lowercase letters too, like your example shows.

Upvotes: 2

Syntax
Syntax

Reputation: 2103

Array.prototype.indexOf

$(document).ready(function(){
    var cars = ['mercedes','nissan','ferrari','bmw','fiat','toyota','renault','peugeot','kia'];
    $('.hide').hide();
    $('button').click(function(){
        if(cars.indexOf($('#search').val()) !== -1){
            $('.h1').show();
            $('.h2').hide();
        } else {
            $('.h2').show();
            $('.h1').hide();
        };
    });
});

http://jsfiddle.net/CWHDv/

Upvotes: 3

Related Questions