Ofcdan Ofcdan - 3 months ago 11
Javascript Question

HTML random number to text

I have this code. Which when you press "RUN" It prints a random number. I need some help (not sure where to start) to when it prints a random number it also prints text associated with that number. Example if it generates any number from 1-5 it will say "Hello" and if it generates 7 it will say "Wassup". Any help is appreciated.

<body>
<script type="text/javascript">
function RandomID() {
var rnd = Math.floor(Math.random() * 11);
document.getElementById('id').value = rnd;
}
</script>
<button class="button"onclick="RandomID();" style="font-family: sans-serif;">RUN</button>
<input class="input" type="text" id="id" name="id" size="3" readonly />
</body>
</html>


https://jsfiddle.net/j9dcp2t4/

Answer

You just need to use an if..else statement:

function RandomID() {
  var value;
  var rnd = Math.floor(Math.random() * 11);

  if (rnd === 7)
    value = "Wassup";
  else if (rnd <= 5)
    value = "Hello";
  else
    value = rnd;

  document.getElementById('id').value = value;
}
<button class="button" onclick="RandomID();" style="font-family: sans-serif;">RUN</button>
<input class="input" type="text" id="id" name="id" size="3" readonly />