-1

How can I create an input with a random value?

For example:

I have 3 possibles values for a given input:

[ 'Value 1',
  'Value 2',
  'Value 3' ]

And I want one of these 3 values entered in the <input> randomly and automatically.

2 Answers2

1

Something like this?

var x = Math.random();
var y;
if (x < 1/3)
    y = "VALUE 1";
else if (x < 2/3)
    y = "VALUE 2";
else
    y = "VALUE 3";
alert(y);

Assuming you want each of the values to be chosen with equal probability.

Yimin Rong
  • 1,890
  • 4
  • 31
  • 48
1

var randomvalue = ['one','two','three'];//set what values you want 

var index = Math.floor(Math.random() * (2 - 1 + 1));//generate random number for index 
console.log(index)
//Note:set 2 as max and 1 as min because in array i set only 3 values so the number will be random from 0-2 where 0 is first item because it is index
$("#test").val(randomvalue[index])//setting the random value as input text
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test"/>
  1. Using .val() to set the random value
  2. Using array to have selection for the value for input
  3. Lastly generating random whole number to be use as index
guradio
  • 15,524
  • 4
  • 36
  • 57
  • Your random generator is not right. If you want random numbers from 0 to 2, you need to multiply by 3. Also you could make it generic `var index = Math.floor(Math.random() * randomvalue.length);` – Olivier De Meulder Jan 20 '17 at 14:45