gpt4 book ai didi

javascript - javascript如何获取输入值

转载 作者:行者123 更新时间:2023-12-02 23:35:59 25 4
gpt4 key购买 nike

我目前正在尝试获取用户选择的号码的输入字段值,但由于某种原因我无法这样做。

我已经尝试将其设为 id,然后执行 document.getElementById("testing").value 但没有成功。

这是我当前的代码:

<section class="generate">
<div class="container">
<h3>Generate a number between </h3>
<form>
First number
<input id="testing" type="number" name="firstnumber" value="First number">
<br> Second number
<input type="number" name="secondnumber" value="Second number">
<br>
<input type="submit" value="Generate random number">
<script>
var secondNumber = document.getElementById('testing').value
var randomNumber = Math.floor(Math.random() * secondNumber);
console.log(randomNumber);
console.log(secondNumber);
</script>
</form>
</div>
</section>

最佳答案

您需要在事件监听器中运行代码,而不是在页面首次加载时运行。

document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault(); // prevent form from really submitting
var secondNumber = document.getElementById('testing').value
var randomNumber = Math.floor(Math.random() * secondNumber);
console.log(randomNumber);
console.log(secondNumber);
});
<section class="generate">
<div class="container">
<h3>Generate a number between </h3>
<form>
First number
<input id="testing" type="number" name="firstnumber" value="First number">
<br> Second number
<input type="number" name="secondnumber" value="Second number">
<br>
<input type="submit" value="Generate random number">
</form>
</div>
</section>

关于javascript - javascript如何获取输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56298802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com