2

目前,我正在尝试设置我的联系表格,以便在输入无效电子邮件时提供错误消息。当提交空白或不正确的电子邮件时,页面应执行以下操作:

  • 注册文本更改为“重试”
  • 输入字段中出现红色文本,说明“输入的地址无效”

当用户专注于输入字段,或按下“重试”时;所有表单元素都应该恢复到原来的状态。我已经能够使用 onFocus 方法让文本从红色变为黑色。我试图创建一个名为 reset 的小 javascript,我希望将 DIV 文本从“重试”更改回“注册”。

我确定我的问题出在 Javascript 上。有人可以指出我正确的方向吗?:)

代码参考:http: //itsmontoya.com/work/playdeadcult/indextest.php

4

3 回答 3

0

试试这个:

function validate() {
    if($("#buttonDiv").html()== 'Retry')
    {
        // oops! They are trying to get back to where they were by 
        // re-clicking retry. Let's reset this thing
        reset()
        return false;
    }
    var emDiv = document.getElementById('email') // only look up once.
    if(emDiv) {
        // the space after the . should allow for 6 long
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/;
        var address = emDiv.value;
        // good form issue -- never use == false. use !
        if(!reg.test(address)) {
            emDiv.value = 'Address entered not valid';
            emDiv.style.color = '#bf4343';
            emDiv.style.fontSize = '12px';
            $("#buttonDiv").html( 'Retry' );
            return false;
        }
    }
}
于 2011-08-30T22:12:57.393 回答
0

一种方法是使用 html:

<form action="" method="post">
    <fieldset>
        <label for="emailAddress">Sign up for the newsletter</label>
        <input type="text" id="emailAddress" name="email" />
        <button id="submitButton" type="submit">Submit</button>
    </fieldset>
</form>

和 JavaScript:

var emailEntry = document.getElementById('emailAddress');
var button = document.getElementById('submitButton');
var defaultButtonText = button.innerHTML;

emailEntry.onblur = function(){
    var val = this.value;

    // the following IS NOT a valid test of email address validity
    // it's for demo purposes ONLY

    if (val.length < 5 && val.indexOf('@') == -1){
        button.innerHTML = 'retry';
        button.style.color = 'red';
    }
    else {
        button.innerHTML = defaultButtonText;
        button.style.color = 'black';
    }
};

button.onclick = function(){
    // prevent submission of the form if the email was found invalid
    // and the innerHTML was therefore set to 'retry'
    if (this.innerHTML == 'retry'){
        return false;
    }
};

JS 小提琴演示

于 2011-08-30T22:09:49.927 回答
0

它只是您需要帮助的 reset() 函数的注释块吗?如果是这样,您可以尝试它的 jQuery 版本,因为您已经加载了 jQuery =)

以下是用于将文本颜色更改为红色的 reset() 函数:

$('#email').val('').css('color', '#FF0000').css('font-size', '18px');

以下是用于将文本颜色更改为黑色的 blur() 函数。将此附加到您的电子邮件输入文本框中,您应该设置:

$('#email').blur().css('color', '#000000');
于 2011-08-30T21:55:02.453 回答