Get number from user input and display in console with JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

You can use # to get the value when user clicks the button using document.querySelector(“”); Following is the JavaScript code −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<div class="container container-fluid">
<p><strong> Example:</strong> choose a number between 1 to 100</p>
<div class="form-group">
<label for="number">Give a number:</label>
<input id="inputNumber" value="" type="text" name="number" />
<p id="output"></p>
<button class="btn btn-dark" id="choose" type="submit">Click Me</button>
   function example() {
      let btn = document.querySelector("#choose");
      let randomNumber = Math.ceil(Math.random() * 100);
      btn.onclick = function() {
         let givenNumber = document.querySelector("#inputNumber").value;
         let valueInt = parseInt(givenNumber, 100);
         console.log(randomNumber, givenNumber);

To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.


Add a value −

On clicking the button Click Me, the same is visible in Console −

Published on 16-Jul-2020 10:21:30