Jari
Jari

Reputation: 41

jQuery check if value of input is in array

I'm trying to check if the value of an input field is in the array but it doesn't seem to work.

This is what I have tried:

var postcode1 = [];
    for (var i = 21000; i < 21999; i++) {
        postcode1.push({ val: i, text: i });        
    }
    console.log(postcode1);

    $('#fw_form_field_146').blur(function() {
        var val = $("#fw_form_field_146").val();
        if( $.inArray(val, postcode1) > -1 ) {
            alert('test');
        }
    });

The array is outputting in console.log but the check doesn't work when i fill in the input field.

Upvotes: 2

Views: 150

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

Since postcode1 it's an array which contains val-text values, you have to use map method by passing a callback provided function as argument.

Also, you need to use Number constructor because the value returned from input it's a string and your given array contains primitive numbers

var postcode1 = [];
for (var i = 21000; i < 21999; i++) {
    postcode1.push({ val: i, text: i });        
}

$('#fw_form_field_146').blur(function() {
    var val = $(this).val();
    if( $.inArray(Number(val), postcode1.map(({val}) => val)) !== -1 ) {
        alert('test');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fw_form_field_146"/>

Another approach it to use includes method.

var postcode1 = [];
for (var i = 21000; i < 21999; i++) {
    postcode1.push({ val: i, text: i });        
}

$('#fw_form_field_146').blur(function() {
    var val = $(this).val();
    if(postcode1.map(({val})=> val).includes(Number(val))) {
        alert('test');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fw_form_field_146"/>

Upvotes: 1

Use this instead since you need to check on the objects in the array and not the array itself.

$('#fw_form_field_146').blur(function() {
  var val = $("#fw_form_field_146").val();
  if (postcode1.filter((e) => e.val == val).length > 0) {
    alert('test');
  }
});

Demo

var postcode1 = [];
for (var i = 21000; i < 21999; i++) {
  postcode1.push({
    val: i,
    text: i
  });
}

$('#fw_form_field_146').blur(function() {
  var val = $("#fw_form_field_146").val();
  if (postcode1.filter((e) => e.val == val).length > 0) {
    alert('test');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fw_form_field_146" />

Upvotes: 0

Shai Aharoni
Shai Aharoni

Reputation: 1957

Try using findIndex instead of inArray, which will allow you to have a more accurate search conditions. Like this:

 if (postcode1.findIndex((item) => item.val.toString() === val) > -1 ) {
            alert('test');
   }

Upvotes: 0

Related Questions