0

我创建了一个 HTML 表单,其中有许多不同的文本框。我想要做的是创建一个 javascript 脚本,该脚本将在其中没有文本的框旁边显示小图像。这是我想做的一个例子:

在此处输入图像描述

目前我已经创建了以下脚本,它可以根据需要验证表单,但是它只显示一个弹出框,因为我不知道如何显示图像/文本。这是我的代码:

    <script type="text/javascript">
    function validateForm()
    {
        var x=document.forms["email_form"]["name"].value;
        if (x==null || x=="")
        {
            alert("Please enter your name in the box provided.");
            return false;
        }

        var x=document.forms["email_form"]["email"].value;
        if (x==null || x=="")
        {
            alert("Please enter your e-mail address in the box provided.");
            return false;
        }

        var x=document.forms["message-title"]["name"].value;
        if (x==null || x=="")
        {
            alert("Please enter a message title in the box provided.");
            return false;
        }

        var x=document.forms["email_form"]["message"].value;
        if (x==null || x=="")
        {
            alert("Please enter your message in the box provided.");
            return false;
        }
    }
    </script>

请有人能指出我正确的方向吗?

4

2 回答 2

1

您可以在输入元素旁边放置错误图像元素,但将显示属性隐藏在 css 中。您可以为链接到其输入元素的每个错误图像设置一个 id。例如,对于电子邮件输入,除了它之外还有和 img 元素。有一个像这样的初始 css ->

#email_form img{
    display: none;
}

然后在您的javascript中,只需显示隐藏的图像 -

    var x=document.forms["email_form"]["email"].value;
    if (x==null || x=="")
    {
        var error_image = document.getElementById('error_email');
        error_image.style.display = 'inline';
        alert("Please enter your e-mail address in the box provided.");
        return false;
    }
于 2012-05-24T21:44:30.333 回答
1

在你的 CSS 中定义一个类

.validateimage
{
 display:none;
}

并将该类分配给所有图像标签,例如

<img class="validateimage" id="image1">
.
.
.

然后

 <script type="text/javascript">
        function validateForm()
        {
            var x=document.forms["email_form"]["name"].value;
            if (x==null || x=="")
            {
                document.getElementById('image1').style.display='block';
                return false;
            }

            var x=document.forms["email_form"]["email"].value;
            if (x==null || x=="")
            {
                document.getElementById('image2').style.display='block';

                return false;
            }

            var x=document.forms["message-title"]["name"].value;
            if (x==null || x=="")
            {
                document.getElementById('image3').style.display='block';
                return false;
            }

            var x=document.forms["email_form"]["message"].value;
            if (x==null || x=="")
            {
                document.getElementById('image4').style.display='block';
                return false;
            }
        }
        </script>
于 2012-05-24T21:48:49.957 回答