2011-01-23 47 views
0

我有一個簡單的JavaScript函數來檢查,如果一個字段不爲空:我如何可以檢索字段名稱

function notEmpty(field , alert_text){ 
if (field.val() === "" || 
    field.val() === null || 
    field.length === 0) { 
    if (alert_text){ 
     alert ('Error: please enter some text - ' + alert_text); 
    } // end if 
    field.addClass('hightlight'); 
    field.focus(); 
    return false; 
} // end if 
else { 
    field.removeClass('hightlight'); 
    return true; 
} // end else 

我想字段的名稱在警報顯示,而無需使用alert_text參數。我嘗試了一大堆東西,沒有運氣,所以我已經離開了函數,我使用alert_text參數來傳遞字段名稱。我所有的表單輸入標籤都是這樣的:

<input type=  "text" 
    name=  "artist" 
    id=  'artistfield' 
    size=  "60" 
    tabindex= "1" /> 

所以他們都有'name'定義。必須有辦法將它放入我的警戒盒,但我還沒弄明白。我相信這很容易,我只是對此很陌生。謝謝。

回答

0

可以檢索與此名稱:

field_name = field.attr('name'); 
0

您可以使用jQuery的attr()方法來獲得域名(和幾乎所有其他HTML屬性):

function notEmpty(field) { 
    if (field.val() === "" || field.val() === null || field.length === 0) { 
     if (field.attr('name')) { 
      alert('Error: please enter some text - ' + field.attr('name')); 
     } 
     field.addClass('hightlight'); 
     field.focus(); 
     return false; 
    } else { 
     field.removeClass('hightlight'); 
     return true; 
    } 
} 
0

您可以使用:

field.attr('name')

要得到name屬性來自該字段。如果您想要字段ID,例如您可以更改nameid

相關問題