jQuery

jQuery Alert Array Values Examples

Processing an array to retrieve its indices and values are different from processing values of other variables in jQuery. In this article, I am going to discuss how to alert array values using jQuery. We will alert array values along with  keys/indices for each of these values using jQuery. This neat way will be immensely useful when you need to debug your jQuery code to see/read/get contents of an array along with keys in jQuery. So read on to find out more how this article can help you.

How to Get / Alert / Print all values in array using jQuery

Let’s take an example. Assume that we have an array in our jQuery code. Now we want to be able to click a button and alert each of the array values along with it’s key so that we can see alert array value.

Example: Here is the full source code to print / alert array values using jQuery

<html>
<head>
<title>jQuery Declare Array | Declare array with values using jQuery Example</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>

<body>

<input type="submit" name="btn_alert" id="btn_alert" value="Alert array values / keys" />

<script type="text/javascript">

$(document).ready(function() {

//Declare an array
var fruits_array = ['mango', 'apple', 'grapes'];

$('#btn_alert').click(function(){

$.each(fruits_array, function(key, value) {
alert('Array Key is: '+ key + ' \n Array Key value is: ' + value);
});

return false;

});

});

</script>
</body>
</html>

When you run the above code, you won’t see anything on the screen except a button. This is because we have declared our array in jQuery. This array is not an element on the webpage, rather it is an array declaration in the code. So when when you click the button, the array key / indices are alerted along with the key value on next line, in a loop.

I have found this trick to be immensely useful when I need to check all values of array and/or to debug them. And since this also gets array keys, it’s even more useful.

Simple, isn’t it?

Do you know of any other ways to use jQuery to alert array values? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*