简体   繁体   中英

How to output a value of a function with parameters onclick in HTML?

I have a function that outputs a random number and I want to output the value below the button when it's clicked.

<!DOCTYPE html>
<html>
<body>

<form>
  <input type="button" value="Click me" onclick="genRand()">
</form>

<script type="text/javascript">
function genRand(min, max, decimalPlaces) {  
  var rand = Math.random()*(max-min) + min;
  var power = Math.pow(10, decimalPlaces);
  return Math.floor(rand*power) / power;
}
</script>

</body>
</html>

If I want the rest of the page to stay when the button is clicked I believe I need to use innerhtml, but I'm having no luck working out how to incorporate it into the code.

I'm new to html and javascript, so any help is really appreciated.

Something like this:

 function genRand(min, max, decimalPlaces) { var rand = Math.random()*(max-min) + min; var power = Math.pow(10, decimalPlaces); var result = Math.floor(rand*power) / power; document.getElementById("result").innerHTML = result; }
 <input type="button" value="Click me" onclick="genRand(0,10,2)"> <div id="result"></div>

You need to pass values when you are calling the function.

<input type="button" value="Click me" onclick="genRand('Minimum Value', 'Maximum Value','Decimal Places')">

For Eg:

<input type="button" value="Click me" onclick="genRand(1,10,2)">

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