Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check all values in an array are same

I have a webpage that has a textbox.

When the user enters information into it, it makes a AJAX call to see if the entry is valid, if not it disables a button.

They can also add up to 10 textboxes which is done via jQuery Templates. At the moment each textbox has a class of serial and when a serial textbox is blurred it does this check.

If they enter a invalid serial it will disable the button but if they add a new textbox and that is valid the button is now enabled which is wrong as there is one still invalid.

The only way I can think to do this is to add a 1 or 0 to an array for each textbox and once all elements in the array are 1 then enable the button. Is that a good approach, if not please explain a better one. If it is a good approach how do I check all values in a javascript array are the same?

Thanks

like image 664
Jon Avatar asked Jun 08 '11 10:06

Jon


People also ask

How do you check all values of an array are equal or not in Javascript?

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.

How do you check if an array has all the same values Java?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

This sounds like a good approach. You can check for equal elements in a javascript array using this simple javascript function. You may paste this to a firebug console to check its functionality.

// check if all elements of my_array are equal, my_array needs to be an array
function check_for_equal_array_elements(my_array){
  if (my_array.length == 1 || my_array.length == 0) {
     return true;
  }
  for (i=0;i<my_array.length;i++){
     if (i > 0 && my_array[i] != my_array[i-1]) {
       return false;
     }
  }
  return true;
}

//Example:
var my_array = [];
my_array.push(5);
my_array.push(5);

// will alert "true"
alert("all elements equal? "+check_for_equal_array_elements(my_array));

my_array.push(6);
// will alert "false"
alert("all elements equal? "+check_for_equal_array_elements(my_array));
like image 125
Thariama Avatar answered Oct 11 '22 14:10

Thariama