How can I make a button with js that shows a random letter when I click it.
Asked
Active
Viewed 5,750 times
0
-
1Math.random(); function could help. – Ashok kumar Nov 14 '16 at 10:39
-
What would be valid letters to produce? – DevDig Nov 14 '16 at 10:40
-
@DevDig all lowercase letters – milan Nov 14 '16 at 10:41
-
math.random to get index from array with valid letters? – Kevin Kloet Nov 14 '16 at 10:41
-
1Possible duplicate of [Generate random string/characters in JavaScript](http://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript) – Liam Nov 14 '16 at 10:41
-
Possible duplicate of [Random alpha-numeric string in JavaScript?](http://stackoverflow.com/questions/10726909/random-alpha-numeric-string-in-javascript) – Ashok kumar Nov 14 '16 at 10:42
-
It needs to be for a game, when you get a random letter you have to awnser with that letter – milan Nov 14 '16 at 10:42
-
`onclick="alert('t') // randomly chosen by a stranger on the internet"` – user3297291 Nov 14 '16 at 10:44
3 Answers
3
Use Math.random
method along with String.fromCharCode
method.
console.log(
String.fromCharCode(
Math.floor(Math.random() * 26) + 97
)
)

Urielzen
- 476
- 7
- 17

Pranav C Balan
- 113,687
- 23
- 165
- 188
1
Try this code:
document.getElementById("rndletter").addEventListener("click", function() {
var result = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97);
document.getElementById("result").innerText = result;
});
<button id="rndletter">Generate random letter</button>
<div id="result"></div>

DontVoteMeDown
- 21,122
- 10
- 69
- 105
0
Try This One :
HTML File
<form name="randform">
<input type="button" value="Create Random String" onClick="randomString();">
<input type="text" name="randomfield" value="">
</form>
Javascript File
<script>
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>

Sachin Sanchaniya
- 996
- 1
- 8
- 16