user2979933
user2979933

Reputation: 1

OnClick event error

function setVisibility('sub1'){
   var element = document.getElementById('bt1');
   if( 'none' == element.style.display ){
       element.style.display = 'block';

   }else{
       element.style.display = 'none';

   }
   return false;
}

Ok so that is my javascript.. I have several buttons (sub1,sub2,sub3, and sub4) all showing different divs(bt1,bt2,bt3 and bt4)

<input id='bt1' type="image" src='button.png' alt="Submit" onclick="setVisibility('sub1');";>

That is the button itself coded into my html and then the div it shows is a simple div:

<div style="display: none;" id='sub1'>Text Goes Here</div>

But when i click the button nothing happens, I am confused as to what I am doing wrong, so if anyone would be so kind as to point out my mistake. Thanks

EDIT: The Html error deleting the extra ; didnt work, taking the ' away from sub made the 4th button appear and disappear

Upvotes: 0

Views: 68

Answers (3)

aksu
aksu

Reputation: 5235

You must declare function parameters whitout apostrophes; like this:

function setVisibility(sub){
  var element = document.getElementById(sub);

Upvotes: 0

Travis J
Travis J

Reputation: 82277

The issue here is that you have an invalid variable definition in your function. Instead of a string, it should define a variable that you can use target the element in question.

function setVisibility(subId){
 var element = document.getElementById(subId);
 ...

There is also a syntax error in your HTML as others noted in comments on your post, namely:

<input id='bt1' type="image" src='button.png' alt="Submit" onclick="setVisibility('sub1');";>

has an extra ; at the end before the >. To be compliant, self closing elements like this should technically also end in an /. For example:

<input id='bt1' type="image" src='button.png' alt="Submit" onclick="setVisibility('sub1');" />

Upvotes: 1

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11707

function setVisibility(id){ 
   var element = document.getElementById(id);
     if( 'none' == element.style.display ){ 
         element.style.display = 'block';
     }else{ 
          element.style.display = 'none';  
     } return false;
 }

try this

Upvotes: 0

Related Questions