0

I have a code that shows a hidden div when a "?a='enter div number'"code was entered on the last part of the url.

<html>
<title> </title>
<head> 
</head>

<body>
<div id="tab1" style="display:none" > 
<p> "This is div 1" </p>
</div>

<div id="tab2" style="display:none"> 
<p> "This is div 2" </p>
    </div>

        <div id="tab3" style="display:none">
        <p> "This is div 3" </p>
        </div>
    </body> 
<script type="text/javascript">

if (window.location == 'http://localhost/assignment.html'){
document.getElementById("tab1").style.display="block";
}

if (window.location == 'http://localhost/assignment.html?a=2'){
document.getElementById("tab2").style.display="block";
}

if (window.location == 'http://localhost/assignment.html?a=3'){
document.getElementById("tab3").style.display="block";
}else{
document.getElementById("tab1").style.display="block";
}



</script>


</html>

somehow when I enter http://localhost/assignment.html?a=2 the result gives a "this is div1" and "this is div2"

2 Answers 2

1

Your last elsestatement only applies to your last if statement and so tab1 is always shown when a != 3. I think you meant to use else if:

if (window.location == 'http://localhost/assignment.html') {
    document.getElementById("tab1").style.display = "block";
} else if (window.location == 'http://localhost/assignment.html?a=2') {
    document.getElementById("tab2").style.display = "block";
} else if (window.location == 'http://localhost/assignment.html?a=3') {
    document.getElementById("tab3").style.display = "block";
} else {
    document.getElementById("tab1").style.display = "block";
}
Sign up to request clarification or add additional context in comments.

1 Comment

follow up question. Can I store the window.location on a variable and make it static then use it for comparison inside elseif?
0
if (window.location == 'http://localhost/assignment.html?a=3'){
   document.getElementById("tab3").style.display="block";
}else{ // Problem is in this else statment
   document.getElementById("tab1").style.display="block";
}

In this part of code you check if location is not http://localhost/assignment.html?a=3 show 'tab1' div. You can delete this part ( from else ).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.