Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gabrieltomonari's avatar

Generate random number into text box

Hi there!

This might look a little dumb, but I'm a beginner... I need to generate a random number by hitting a button and then display it within a text box. How can this be achieved? JS?

0 likes
5 replies
colender's avatar

You don't really need JS to do this unless you want to use ajax. But first you would just create the view form with the text box and button and have the action set to a function in the controller that does the random Number then redirect to the form page with the number inside the text box.

here are a few things to read to kinda help you get started. http://laravel.com/docs/4.2/routing http://laravel.com/docs/4.2/controllers http://laravel.com/docs/4.2/responses http://php.net/manual/en/function.mt-rand.php (to generate random ints)

1 like
sitesense's avatar
Level 19

No need for ajax at all, it could be as simple as this: https://jsfiddle.net/ofpab4e9/1/

<button id="button" onclick="getElementById('random-number').value=Math.floor(Math.random()*10000)">Create Random Number</button>
<br>
<input id="random-number" value="" />
2 likes
gabrieltomonari's avatar

Thank you so much @sitesense ! I actually knew it was possible with JS, but I wanted to make sure it was the best option in this case. Also thank you @colender for the help!

Vikrant's avatar

i want that random number generate in sequence. limit of number 3 digit only. like 1,2,3,.... upto 999 how i can achived

Please or to participate in this conversation.