Refresh message after every user attempt

时间:2015-06-30 19:24:12

标签: javascript jquery

I am trying to have a success or failure message pop up every time the user enters input and clicks out of the input area. Here's what I currently have:

function checkUsername() {
    var username = document.getElementById("username").value;

    if (username.length == 0) {
        document.getElementById("username_message").className = "failure";
        document.getElementById("username_message").innerHTML = "Username is too short.";
        $("#username_message").fadeOut(3000);

    } else {
        document.getElementById("username_message").className = "success";
        document.getElementById("username_message").innerHTML = "Valid!";
        $("#username_message").fadeOut(3000);
    }

In terms of the input field, I have the following:

<input type="text" id="username" onblur="checkUsername()" autofocus>

When I run this code and click out of the input field, the error message displays, but to get any other message to display, I have to refresh the page. The input field is currently inside a form, so I was wondering how I could get the message(s) to show every time, instead of having to refresh the page? Once one message shows, the other one doesn't unless I refresh.

2 个答案:

答案 0 :(得分:4)

jQuerys start firefox.exe 方法将不透明度淡化为0,然后在元素上设置fadeOut。你需要“逆转”这个。

所以将功能更改为:

display:none

function checkUsername() { var username = document.getElementById("username").value; if (username.length == 0) { document.getElementById("username_message").className = "failure"; document.getElementById("username_message").innerHTML = "Username is too short."; } else { document.getElementById("username_message").className = "success"; document.getElementById("username_message").innerHTML = "Valid!"; } $("#username_message").stop(true, true).show().fadeOut(3000); } 会立即使淡出效果结束,然后将不透明度设置为1.使用jsFiddle

答案 1 :(得分:-1)

innerHTML replace everything inside use append() instead.

var error = '<p id="errorCode01">some error</p>'; 

// if fail test 

$('#username_message').append(error);

// if pass test get the error

$('#username_message').find('#errorCode01').remove();