2010-07-22 62 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-的最元件”)值=“字段。不能为空!”;