简体   繁体   中英

dynamically showing and hiding divs with javascript

I currently have the following code for my login system:

function handleLogin() {
    var e = $("#username").val();
    var p = $("#password").val();

    if(e != "" && p != "") {
        $.ajax({ 
            type: 'POST', 
            url: 'http://localhost/php/log.php', 
            crossDomain: true,
            data:  {username: e, password :p},
            dataType: 'json', 
            async: false,
            success: function (response) { 
                if (response.success) { 
                    alert("Your login worked");
                    $('#loginTest').html(e);
                } else {
                    alert("Your login failed");
                }
            },
            error: function(error) {
                alert('Could not connect to the database' + error);
            }
        }); 
    } else {
        alert("You must enter username and password");
    }
    return false;
}

When the login has worked, I get the correct alert, but then I want the login div to hide, and the div beneath it to show with the username (e) in it.

So basically I just need to work out how to hide the current div, then show another one.

The login div is called #loginPage and the div below it is called #loginTest

You can use hide() and show() :

if (response.success) { 
    $('#loginPage').hide();
    $('#loginTest').show().html(e);
} 

There are also fadeIn , fadeOut , slideUp , slideDown to deal with the display/hiding of elements. You could even use animate to define your own transition. The API is always your friend in these situations.

To show and hide any particular HTML element you can use show() and hide() functions of that element. Initially you can hide your loginTest div and only show loginPage div.

Try this:

function (response) { 
                if (response.success) { 
                    $(#loginPage).hide(); //Hiding login page div
                    $(#loginTest).show(); //Showing login test div
                    alert("Your login worked");
                    $('#loginTest').html(e);
                } else {
                    alert("Your login failed");
                }

You can also add time for showing and hiding your DIV. Like $(#loginPage).hide("fast"); and $(#loginTest).show("slow"); . It totally depends upon you what is your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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