Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a random value from an array?

Tags:

javascript

I'm using the jQuery validate plugin, and would like to return a random value on success.

Right now I'm trying to use:

     var success_message = new Array ();      success_message[0] = "Good!";      success_message[1] = "Ok!";      success_message[2] = "Great!";      success_message[3] = "Perfect!";      success_message[4] = "Nice!";      success_message[5] = "Awesome";       var i = Math.floor(5 * Math.random()) 

Then where I need to output the value I use:

 $(document).ready(function(){      var validator = $(".contactform").validate({         success: function(label) {            label.addClass("valid").text(success_message[i])         }      }); //end form validate code  }); 

This selects a random value but uses the same value for each success message instead of selecting a different one for each field.

like image 389
Brooke. Avatar asked Aug 05 '10 23:08

Brooke.


People also ask

How do you generate a random number in an array?

In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.

How do you select a random value from an array in Python?

Use the numpy. random. choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.

How do you select a random value from an array in Java?

Java has a Random class in the java. util package. Using it you can do the following: Random rnd = new Random(); int randomNumberFromArray = array[rnd.


1 Answers

You can store the messages array and calculate the message to show as you go, like this:

var messages = ["Good!", "Great!", "Awesome!", "Super!", "Nice!"]; function getMessage() {    return messages[Math.floor(Math.random() * messages.length)]; } 

Give it a try here, then just call getMessage in your .text() call, like this:

label.addClass("valid").text(getMessage()); 
like image 143
Nick Craver Avatar answered Sep 28 '22 08:09

Nick Craver