[英]Passing an id through a function parameter
嘗試通過將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')"/>
錯誤信息
錯誤:無法獲取未定義或空引用的屬性“值”
您輸入的ID是“ 19”而不是“ numberbox19”
您的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,則只需在一個位置而不是兩個位置進行更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.