[jquery] JS jQuery - check if value is in array

I am more of a PHP person, not JS - and I think my problem is more a syntax problem ..

I have a small jQuery to "validate" and check input value .

It works ok for single words, but I need array.

I am using the inArray() of jQuery .

var ar = ["value1", "value2", "value3", "value4"]; // ETC...

        jQuery(document).ready(function() {

            jQuery("form#searchreport").submit(function() {
            if (jQuery.inArray(jQuery("input:first"), ar)){ 
                      //if (jQuery("input:first").val() == "value11") { // works for single words
            jQuery("#divResult").html("<span>VALUE FOUND</span>").show();
            jQuery("#contentresults").delay(800).show("slow");
                return false;
              }

        // SINGLE VALUE SPECIAL CASE / Value not allowed 
               if (jQuery("input:first").val() == "word10") {

                jQuery("#divResult").html("YOU CHEAT !").show();
                jQuery("#contentresults").delay(800).show("slow");

                return false;
              }

        // Value not Valid

              jQuery("#divResult").text("Not valid!").show().fadeOut(1000);

              return false;
            });

        });

now - this if (jQuery.inArray(jQuery("input:first"), ar)) is not working right .. every value that I put will be validated as OK . (even empty)

I need to validate only values from the array (ar) .

I tried also if (jQuery.inArray(jQuery("input:first"), ar) == 1) // 1,0,-1 tried all

what am i doing wrong ?

Bonus question : how to do NOT in array in jQuery ?? (the equivalent of PHP if (!in_array('1', $a)) - I sw somehre that it will not work , and need to use something like this : !!~

This question is related to jquery arrays validation

The answer is


The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)


Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery