使用 Vanilla JavaScript 从输入文本中获取更新值

Getting updated value from Input text using Vanilla JavaScript

背景 -
我是 JavaScript 世界的新手,正在开发一个小型应用程序来生成一个范围内的随机数。用户采用两个输入,即范围的“minValue”和“maxValue”,并通过单击“生成”按钮生成随机数。

问题-
在没有任何框架的情况下使用 vanilla JavaScript 一次又一次更新时如何从这两个数字字段获取输入?

我想提醒用户,如果他们在点击生成按钮之前将值反之亦然。意味着如果任何用户在 maxValue 输入中输入最小值,在 minValue 输入中输入最大值。一旦用户停止,我只想发出警报。我知道点击生成按钮后可以轻松完成,但出于学习目的,我想以这种方式执行操作。

现在我在程序开始时得到变量 MinValue 和 maxValue 的空白值,之后该值不会通过更改数字字段值来更新。

const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;

// console.log(numberGenerator);
// console.log(button);
//console.log(minValue);
//console.log(maxValue);

let generateRandomNumber = (max, min) => {
  randomNumber = Math.floor(Math.random() * (max - min)) + min
  numberGenerator.innerHTML = randomNumber;
};

button.addEventListener("click", generateRandomNumber, minValue, maxValue);
<div class="outer-box">
  <div class="generator-box">
    <h1> Random Number Generator </h1>
    <div class="inputs">
      <label for="min">Min Value:</label>
      <input type="number" id="min" name="min" placeholder="Enter min value"><br><br>
      <label for="max">Max Value:</label>
      <input type="number" id="max" name="max" placeholder="Enter max value"><br><br>
    </div>
    <span class=random-number>Click to generate</span>
    <hr>
    <div class="buttons">
      <button class='button1'>Generate</button>
    </div>
  </div>
</div>

谢谢

需要在按钮中添加onclick事件并调用函数

如果您想在单击按钮之前添加最小和最大文本框 onchange 事件并编写您的逻辑

请检查以下方式

<button class='button1' onclick="generateRandomNumber()">Generate</button>

这就是你的功能逻辑。

<script>
    function generateRandomNumber() {
     const numberGenerator = document.querySelector(".random-number");
     const button = document.querySelector(".button1");
     const minValue = document.querySelector("#min").value;
     const maxValue = document.querySelector("#max").value;
     randomNumber = Math.floor(Math.random() * (maxValue-minValue)) + minValue
     numberGenerator.innerHTML = randomNumber;
    }
</script>

要获得您必须输入的更新值

const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;

里面

let generateRandomNumber = () => {...}

如果你把它放在 generateRandomNumber 之外然后它会在页面加载时设置输入的值如果你把它放在 generateRandomNumber 那么它会在调用该函数时重新分配

const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");


let generateRandomNumber = () => {
    var min = document.querySelector("#min").value;
    var max = document.querySelector("#max").value;
    
    min = Math.ceil(min);
    max = Math.floor(max);
    randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    numberGenerator.innerHTML = randomNumber;
};

button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Number Generator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="outer-box">
        <div class="generator-box">
            <h1> Random Number Generator </h1>
            <div class="inputs">
                <label for="min">Min Value:</label>
                <input type="number" id="min" name="min" placeholder="Enter min value"><br><br>
                <label for="max">Max Value:</label>
                <input type="number" id="max" name="max" placeholder="Enter max value"><br><br>
            </div>
            <span class=random-number>Click to generate</span>
            <hr>
            <div class="buttons">
                <button class='button1'>Generate</button>
            </div>
        </div>
    </div>
    <script src='random_number_generator.js'></script>
</body>
</html>

Update:获取输入的更新值(按下按钮之前)

const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const error = document.querySelector(".error");
const minInput = document.getElementById("min");
const maxInput = document.getElementById("max");

var min = 0;
var max = 0;

maxInput.oninput = valueDetected;
minInput.oninput = valueDetected;

function valueDetected(){
  console.log("Max: "+maxInput.value+" & Min: "+minInput.value)
}

let generateRandomNumber = () => {
    min = Math.ceil(min);
    max = Math.floor(max);
    randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    numberGenerator.innerHTML = randomNumber;
};


button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Number Generator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="outer-box">
        <div class="generator-box">
            <h1> Random Number Generator </h1>
            <div class="inputs">
                <label for="min">Min Value:</label>
                <input type="number" id="min" name="min" placeholder="Enter min value" value=0><br><br>
                <label for="max">Max Value:</label>
                <input type="number" id="max" name="max" placeholder="Enter max value" value=0><br><br>
            </div>
            <span class=random-number>Click to generate</span>
            <hr>
            <div class="buttons">
                <button class='button1'>Generate</button>
        </div>
    </div>
    <script src='random_number_generator.js'></script>
</body>
</html>

验证一个

const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const error = document.querySelector(".error");
const minInput = document.getElementById("min");
const maxInput = document.getElementById("max");

var min = 0;
var max = 0;

maxInput.oninput = checkValid;
minInput.oninput = checkValid;

function checkValid(){
  if(parseInt(maxInput.value) < parseInt(minInput.value)){
    button.style.display = "none"; 
    error.style.display = "block";
  }
  else {
    button.style.display = "block"; 
    error.style.display = "none";
    min = minInput.value;
    max = maxInput.value;
  }
}

let generateRandomNumber = () => {
    min = Math.ceil(min);
    max = Math.floor(max);
    randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    numberGenerator.innerHTML = randomNumber;
};


button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Number Generator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="outer-box">
        <div class="generator-box">
            <h1> Random Number Generator </h1>
            <div class="inputs">
                <label for="min">Min Value:</label>
                <input type="number" id="min" name="min" placeholder="Enter min value" value=0><br><br>
                <label for="max">Max Value:</label>
                <input type="number" id="max" name="max" placeholder="Enter max value" value=0><br><br>
            </div>
            <span class=random-number>Click to generate</span>
            <hr>
            <div class="buttons">
                <button class='button1'>Generate</button>
                <span class="error" style="color: red; display: none;">You Cannot Put A  Maximum Value Less Than The Minimum Value</span>
            </div>
        </div>
    </div>
    <script src='random_number_generator.js'></script>
</body>
</html>

  1. 只创建引用元素的变量,例如。 minInputmaxInput
  2. 向元素添加事件侦听器。 'click' 用于按钮,'change' 用于输入,
  3. 使用parseInt并将输入值存储在变量中,
  4. 检查其中是否有 NaN(不是数字),
  5. 生成两个输入都有数字的数字。

如果我是你,我也会给按钮和 .random-number 跨度唯一的 ID,以暗示它们在 javascript 代码中被引用。

const numberGenerator = document.querySelector(".random-number");
const generateButton = document.querySelector(".button1");
const minInput = document.getElementById("min");                 // 1
const maxInput = document.getElementById("max");                 // 1

generateButton.addEventListener('click', generateRandomNumber);  // 2
minInput.addEventListener('change', generateRandomNumber);       // 2
maxInput.addEventListener('change', generateRandomNumber);       // 2

function generateRandomNumber() {
  let min = parseInt(minInput.value);                            // 3
  let max = parseInt(maxInput.value);                            // 3
  const BOTH_INPUTS_GOT_VALUES = !isNaN(min) && !isNaN(max);     // 4
  
  if (BOTH_INPUTS_GOT_VALUES) {                                  // 5
    randomNumber = Math.floor(Math.random() * (max - min)) + min;
    numberGenerator.innerHTML = randomNumber;
  }
}
.inputs {
  margin-bottom: 1rem;
}
<div class="outer-box">
  <div class="generator-box">
    <h1> Random Number Generator </h1>
    <div class="inputs">
      <label for="min">Min Value:</label>
      <input type="number" id="min" name="min" placeholder="Enter min value">
      
      <label for="max">Max Value:</label>
      <input type="number" id="max" name="max" placeholder="Enter max value">
      
    </div>
    <span class=random-number>Click to generate</span>
    <hr>
    <div class="buttons">
      <button class='button1'>Generate</button>
    </div>
  </div>
</div>