我想在javascript函数中使用表单元素的输入值。但是,当我声明变量时,它不会从表单中提取输入值。相反,调试器只是在说; “”
我的代码如下。
HTML:
<input type="number" name="stack" id="stack" min="1" max="600" placeholder="Big Blinds" required>
使用Javascript:
var stack = document.getElementById("stack").value;
任何建议都会很棒。感谢。
答案 0 :(得分:0)
当输入元素仍为空时,您似乎正在获取值。设置变量的代码似乎没有封装在输入元素输入数据后一次运行的函数内,因此代码会立即运行。
您需要确保在输入值后获得值。
这是通过添加在特定时间触发的事件处理函数来实现的。您可以使用各种活动(keyup
,keydown
,input
,表单submit
,按钮click
等)。以下是单击按钮时获取值的示例。
// Get a reference to the button that will trigger the event function
var btn = document.getElementById("btn");
// Get a reference to the input element (do this outside of the function that
// will need it so you don't wind up scanning the document for it over and over).
// Also, set the variable to the element itself, not a property of the element so
// that if you ever need a different property, you don't have to scan the document
// for the element again:
var input = document.getElementById("stack");
// If you intend to use the value of the element across several functions, declare a
// variable that will hold the value outside of all of them.
var stack = null;
// Set the button up to call a function when it gets clicked.
btn.addEventListener("click", function(){
// When clicked, get the value
stack = input.value;
// Do whatever you want with the stored value.
console.log(stack);
});
&#13;
<input type="number" name="stack" id="stack" min="1" max="600" placeholder="Big Blinds" required>
<button id="btn">Get Value</button>
&#13;