尝试通过将 ID 传递给函数参数来获取文本框的值。应该很容易,但我无法理解它。
JavaScript:
function checkfield(id)
{
var field = document.getElementById(id);
if (isNaN(field) == true)
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(textbox);
field.select(textbox);
return false;
}
return true;
}
HTML:
<input type="text" id="numbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield('numbox19')"/>
错误信息
Error: Unable to get property 'value' of undefined or null reference
最佳答案
您的 ID 是 19
,但您将 numberbox19
传递给 Javascript 函数。还有一些语法错误。
尝试:
<input type="text" id="numberbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield(this)"/>
和 JavaScript:
function checkfield(field) // <-- we passed the field in directly from the HTML, using 'this'
{
alert(field.value);
if (isNaN(field.value)) // check the value, not the field itself!
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(); // not "field.focus(textbox);"
return false;
}
return true;
}
这里的好处是,如果您出于任何原因决定更改 ID,您只需更改一处而不是两处。
关于javascript - 通过函数参数传递 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20200492/