user2218497
user2218497

Reputation: 373

check for particular value in an array

I created a dropdown and fetched the option tag values in an array. I want to check whether the textbox value matches with array value.

HTML:

<select>
<option>test1</option>
<option>test2</option>
<option>test3</option>
<option>test4</option>
</select>
<input type="text" id="txt" /> //textbox
<input class="bt" type="button" id="btntest" value="Check for the Value">

I got the array using the following Jquery:

var values = $('select').children('option').map(function (i, e) 
{
return e.innerText;
});

Now values variable holds the result as test1,test2,test3,test4

Question: If user typed "test2" in textbox(txt), How to check whether test2 is available in the array and so on. If user entered anything apart from array values should display an error message.

Please find the fiddle.

Upvotes: 0

Views: 770

Answers (5)

TrejGun
TrejGun

Reputation: 278

As I understand you need automaticlly select that option so its much easier

var value = $('#txt').val();
$('option', 'select').filter(function(){return this.innerText == value;}).prop("selected", true)

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

Fiddle

$('#btntest').click(function () {
   if ($.inArray($('#txt').val(), values) > -1) {
      console.log("available");
   }else{
     console.log("not available");
   }
});

Upvotes: 0

moonwave99
moonwave99

Reputation: 22817

Use jQuery.inArray.

if( jQuery.inArray( yourValue, yourArray) ){ //doStuff }

Upvotes: 0

vborutenko
vborutenko

Reputation: 4443

You can use jquery InArray

jQuery.inArray( $('#txt').val() , values)

Upvotes: 1

Pathik Gandhi
Pathik Gandhi

Reputation: 1344

There is a inbuilt jquery function inArray http://api.jquery.com/jQuery.inArray/

jQuery.inArray("test2", values)

Upvotes: 2

Related Questions