2010-07-22 47 views
0

我想在輸入元素本身中顯示錯誤消息,而不是單獨顯示錯誤消息。我將如何捕獲消息需要顯示的元素?在javascript中捕獲元素

本的代碼:

function checkForm(form) { 

     if (yname.getValue() == "" || yname.getValue() == "Your Name" || name.getValue() == "" || name.getValue() == "Name of the Book" || url.getValue() == "" || url.getValue() == "URL of the Book"){ 
       [id-of-the-element].setTextValue("Field cannot be empty!"); 
      return false; 
     } 

回答

1

你可以在「擴展」你的條件語句:

function checkForm(form) { 
    var result = true; 
    if (yname.getValue() == "" || yname.getValue() == "Your Name") { 
     setErrorMessage(yname); 
     result = false; 
    } else if (name.getValue() == "" || name.getValue() == "Name of the Book") { 
     setErrorMessage(yname); 
     result = false; 
    } else if (url.getValue() == "" || url.getValue() == "URL of the Book") { 
     setErrorMessage(yname); 
     result = false; 
    } 
    return result; 
} 

function setErrorMessage(field) { 
    field.setTextValue("Field cannot be empty!"); 
} 
+0

這是,如果我理解正確的你 - 你需要知道哪些字段爲空 – 2010-07-22 15:10:28

+0

我想有沒有別的辦法? – input 2010-07-22 15:28:02

+0

當然它可以用某種方式重構,例如(yname.getValue()==「」|| yname.getValue()==「Your Name」)可以移入單獨的函數中。 但是沒有一個標準函數可以調用,它會給你什麼字段爲空。但是,可能有,也可能在某個地方,函數獲取表單的空字段。但在你的例子中,你的字段有一些默認值,它們也被視爲一個空值。 – 2010-07-22 15:44:48

0

這是普通的Java腳本代碼,如果你不使用jquery

的document.getElementById( 「ID-的最元件」)值=「字段。不能爲空!」;

相關問題