2013-11-25 26 views
0

嘗試通過將ID傳遞給函數參數來獲取文本框的值。應該很容易,但不能圍繞它包裹我的頭。通過函數參數傳遞一個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

+0

你真的認爲''numberbox19''嗎?導致您的字段名爲「customerZip」,並且ID爲「19」...並且郵政編碼字段觸發驗證另一個數字字段有點奇怪...... – cHao

+0

您爲「getValue」定義了什麼(你打電話給它,但沒有顯示) – scunliffe

+0

@cHao對不起,代碼被更新了。 –

回答

2

你的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以任何理由,你只需要改變它在一個地方而不是兩個。

+0

正是我所需要的。忘了使用這個,一旦你發佈它,我馬上就知道了。 –

2

您輸入的ID是 「19」 而不是 「numberbox19」

+0

已更新的代碼,對不起,這不是我的代碼 –