'jQuery check if value not in array
Tried to get this to work:
var instance_name = $('#instance_name').val();
$("#instance_name").on("blur", function(e){
if (!~$.inArray(instance_name, not_allowed)) {
$("#instance_alert").html("<font color=green>Instance does not exists. Please continue</font>");
} else {
$("#instance_alert").html("<font color=red>Instance exists. Please try another one.</font>");
}
But to no avail.. (Looked into How to check if a value is NOT in an array using jQuery)
Any ideas why it still continues to say Please continue Kindly.
Solution 1:[1]
you can use this: please $.inArray
if(jQuery.inArray("test", not_allowed) != -1) {
console.log("is in array");
} else {
console.log("is NOT in array");
}
Solution 2:[2]
You can use indexOf() method. The indexOf() method searches the array for the specified item, and returns its position. It returns -1 if the item is not found.
var not_allowed = ["test", "noah", "help", "demo"];
$("#instance_name").on("blur", function (e) {
var instance_name = $(this).val();
if (not_allowed.indexOf(instance_name) > -1) {
$("#instance_alert").html("<font color=red>Instance exists. Please try another one.</font>");
} else {
$("#instance_alert").html("<font color=green>Instance does not exists. Please continue</font>");
}
});
Solution 3:[3]
Late answer, but To check if a value IS NOT present in an array, you can use:
if(jQuery.inArray("item", the_array) === -1) {
// item NOT in Array
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Angu |
| Solution 2 | |
| Solution 3 |
