简体   繁体   中英

Onclick button that add random value from array in textarea no refresh

Hey there :) I'm trying to make a function so when composing text, user can click button that fetch random value from array and put in textarea no refresh. My current problem is once page load, it get the random value from array in php and js using onclick, but clicking the button dont get new value, always the same until refresh.

I'm not very JS I only use php and some ajax/jquery refresh call. Here my actual function and codes:

 function randommacro(){
$randomword = array(1, 2, 3, 4, 5);
//$randomword = file('macro/randomword.txt');


shuffle($randomword);

$randomword = $randomword[0];
return $randomword;
}


<script language="javascript" type="text/javascript">
function addtext(text) {
document.myform.message.value += text;
}
</script>

<button class="btn btn-primary" onclick="addtext('<?php echo htmlspecialchars(randommacro()); ?>'); return false">Random Macro</button>

This will allow you to get a random value from your array using javascript.

 <html> <body> <script language="javascript" type="text/javascript"> function addtext() { $randomword = ["Name","Think","Person","Apple","Orange","bananna"]; document.myform.message.value += $randomword[getRandomInt(0,5)]; } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } </script> <form name="myform"> <textarea name="message"> </textarea> <button type="button" onclick="addtext();">Random Macro</button> </form> </body> </html> 

Here is a PHP and Javascript version:

<html>
<body>
  <?php
    // Create your array using PHP
    $RandomTextArray = array("Name","Think","Person","Apple","Orange","bananna");
  ?>
  <script language="javascript" type="text/javascript">
    function addtext() {
      // Create the Javascript version of your PHP array
      $randomword = <?php echo json_encode($RandomTextArray); ?>;

      // Add a new word to the textarea value
      document.myform.message.value += $randomword[getRandomInt(0,<?php echo sizeof($RandomTextArray) ?>)];
    }

    function getRandomInt(min, max) {
      // Returns a random integer between your min and max values (aka: 0 and size of array)
      return Math.floor(Math.random() * (max - min)) + min;
    }
  </script>
  <form name="myform">
    <textarea name="message"></textarea>
    <button type="button" onclick="addtext();">Random Macro</button>
  </form>
</body>
</html>

Try putting it into another variable

$random = $randomword[0]
return $random

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM