sumit kumar
sumit kumar

Reputation: 652

Hide a div section conditionally by java script

I want to hide a div section from javascript, i have code like

$(document).ready(function() {
        var error='<%= session.getAttribute("errormsg") %>';
        alert(error);
        if(error!=null){
            document.getElementById('loginform').style.display = "hidden";
            alert("ok");
        }

    });

here alert(error); is working fine means its printing if error is null or not, But irrespective of this it always print alert("ok");. And document.getElementById('loginform').style.display = "hidden"; never works.

what is wrong in this code.

Upvotes: 0

Views: 588

Answers (5)

prabin badyakar
prabin badyakar

Reputation: 1746

Just use .hide().

**   $(document).ready(function() {
        var error='<%= session.getAttribute("errormsg") %>';
        alert(error);
        if(error!=null){
            $('#loginform').hide()
            alert("ok");
        }

    });**

Upvotes: 2

Junaid Ahmed
Junaid Ahmed

Reputation: 695

use  document.getElementById('loginform').style.display = "none";

it will work fine

Or u can also use document.getElementById('loginform').style.visibility = "hidden";

Upvotes: 0

VPK
VPK

Reputation: 3090

I think using java scriptlet in javascript code is not a good practice as javascript is runs on client side and java scriptlet on server side. I suggest you should use a hidden field say errorMsg and use its value in javascript. as follows,

<input type="hidden" id="errorMsg" value="${errormsg}">

And modify your code as,

$(document).ready(function() {
    var error=document.getElementById('errorMsg').value;
    alert(error);
    if(error!=null){
        document.getElementById('loginform').style.display = "none";
        alert("ok");
    }

});

Also use of none instead of 'hidden' is a good practice unless you want your hidden element to consume space.

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176956

it good if you use undefined in javascript as below

if(typeof variable_here === 'undefined'){
   // your code here.
 };

so for you it will be like

if(typeof error!==null){
            //make use of none insted of hidden to hide element completly
            //if you use hidden it will consume space on you page 
            //with none it will not consume space
            document.getElementById('loginform').style.display = "none";
            alert("ok");
        }

Upvotes: 1

ArinCool
ArinCool

Reputation: 1738

Use:

document.getElementById('loginform').style.display = "none";

Upvotes: 1

Related Questions