Computer >> Computer tutorials >  >> Programming >> Javascript

Get number from user input and display in console with JavaScript


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

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="container container-fluid">
<p><strong> Example:</strong> choose a number between 1 to 100</p>
<form>
<div class="form-group">
<label for="number">Give a number:</label>
<input id="inputNumber" value="" type="text" name="number" />
</form>
<p id="output"></p>
</div>
<button class="btn btn-dark" id="choose" type="submit">Click Me</button>
</body>
<script>
   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);
      };
   }
   example();
</script>
</html>

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.

Output

Get number from user input and display in console with JavaScript

Add a value −

Get number from user input and display in console with JavaScript

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

Get number from user input and display in console with JavaScript