I want to incorporate a random number generator into a user form field.
Then... I need the button disappear after it is clicked, so the user can only generate one number.
I have two codes I have been trying to merge, and just can't seem to get it working.
Any guidance in merging the two (or something else) to achieve what I am trying to do would be helpful.
The first code is the Random Number Generator. Which is fine for generating a random number, but I need that number to appear in a form field.
The second code is a basic 'Disappearing Button' code example.
RANDOM NUMBER GENERATOR:
<html>
<body>
<p id="one"></p>
<button onclick="random()";>Generate</button>
<script>
function random(){
document.getElementById("one").innerHTML = Math.floor(Math.random() * 999999);
}
</script>
</body>
</html>
DISAPPEARING BUTTON CODE:
<script type="text/javascript">
var Text = 'Random Number';
function setInput(button) {
var buttonVal = button.name,
textbox = document.getElementById('input_' + buttonVal);
textbox.value = Text ;
button.style.display = 'none';
}
</script>
<html>
<input class='input' id="input_a1" name="a1" value="<?php {echo $a1;} ?>">
<input type='submit' name='a1' value='x' onclick='setInput(this); return false;'>
</html>
I tried several things, such as...
<html>
<body>
<p id="one"></p>
<button onclick="random()";>Generate</button>
<script>
function random(){
document.getElementById("one").innerHTML = Math.floor(Math.random() * 999999);
button.style.display = 'none';
}
</script>
</body>
</html>
No luck. :(
You can pass this
(refers to the element that triggered the event) to random()
as an argument called button
, then it works fine:
<html>
<body>
<form onsubmit="onSubmit(this, event)">
<p id="one"></p>
<input id="random" name="random" type="hidden">
<button type="button" onclick="generateRandom(this)";>Generate</button>
<button>Submit</button>
</form>
<script>
function generateRandom(button){
document.getElementById('random').value = document.getElementById("one").innerHTML = Math.floor(Math.random() * 999999);
button.style.display = 'none';
}
function onSubmit(form, event){
event.preventDefault();
console.log(...new FormData(form).entries());
}
</script>
</body>
</html>