6

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.

4 Answers 4

5

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");
} 
Sign up to request clarification or add additional context in comments.

Comments

4

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
}

Comments

3

First of all the value of instance_name will not be updated on blur as you are saving the value outside of the blur event.

Hence, you need to move var instance_name = $('#instance_name').val(); inside the blur event listener. When inside the event listener you may use the shorthand $(this).val() to get the value.

For the condition, use indexOf which returns -1 if a value is not in the search array, otherwise it returns the index of the position of the value being searched (i.e 0,1,2...).

Code:

var not_allowed = ["test", "noah", "help", "demo"];
$("#instance_name").on("blur", function (e) {
    // $(this).val() is the value of #instance_name.
    if (not_allowed.indexOf($(this).val()) > -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>");
    }
});

Comments

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>");
    }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.