简体   繁体   English

使用javascript在jsp中显示错误消息

[英]display error message in jsp with javascript

I have a jsp file contains a form and I need to validate the form.我有一个包含表单的 jsp 文件,我需要验证该表单。 The jsp page will be opened as pop-up page and hence I choose not to pop-up the validation message again. jsp 页面将作为弹出页面打开,因此我选择不再弹出验证消息。 Here is my code.这是我的代码。

<script type="text/javascript"> 
    function validateForm() {
        var x=document.forms["myForm"]["name1"].value;
        if (x.trim().length<=4){
            return false;
        }
    }
</script>
<form name="myForm" method="POST" action="write.jsp" onsubmit="return validateForm();">
    Name: <input type="text" name="name1" value="<%=name%>" size="20"/>  <br> 
    Price: <input type="text" name="price"  value="<%=price%>" size="20" /><br> 
    Due time: <input type="text" name="DueTime"  value="<%=dueday%>" size="20" /><br> 
    Location: <input type="text" name="Location"  value="<%=address%>" size="20" /><br> 
    Photo Url: <input type="text" name="url"  value="<%=imagePath%>" size="20" /><br> 
    Description: <input type="text" name="desc"  value="<%=desc%>" size="20" /><br> 
    <input type="submit" name="submit" onclick="window.close()"/>
    <% if(validateForm = false) { %> <a>error message</a> <% } %>
</form>

I am validating for first input "name1" only and the input length is less than 4.我仅验证第一个输入"name1"并且输入长度小于 4。
I'd like to display a error message below the submit button.我想在提交按钮下方显示一条错误消息。 The codes is not working, can anyone help me to fix this?代码不起作用,谁能帮我解决这个问题?

Use document.getElementsByName("name1") instead of document.forms["myForm"]["name1"].value;使用document.getElementsByName("name1")而不是document.forms["myForm"]["name1"].value;

Use as用于

function validateForm()
{
var x=document.getElementsByName("name1").value;
if (x.trim().length<=4)
  {
    alert("Message");
    return false;
  }
}
 document.getElementsByName('name1')[0].value;  

in place of代替

document.forms["myForm"]["name1"].value;

use a span below the submit button在提交按钮下方使用跨度
html html

<span id="error"></span>

script脚本

function validateForm()
                {
                var x=document.getElementsByName('name1')[0].value;
                if (x.trim().length<=4)
                  {
                    document.getElementById("error").innerHTML="atleast 4 letters required in name";
                    return false;
                  }
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM