Nick
Nick

Reputation: 639

Javascript onclick event working to show but not to hide

It's a pretty basic script, but basically im displaying a div on click, and then hiding then div when you click a button title later. i have done this before and it has worked flawlessly. I just cant seem to find out what i did wrong, or am doing wrong. Like i said, the first click() displays perfectly, the second hide() does nothing

JS:

function click1(){
    document.getElementById('form1').style.display='block';
}

function hide1(){
    document.getElementById('form1').style.display='none';
}

HTML:

<tbody>
 <tr>
  <td style="cursor:pointer;" onclick="click1()">
   <div id="form1" style="display:none;">
    <form action="enter.php" method="post">
     <label for="entry1">Entry1</label>
      <input type="text" id="entry1" name="entry1" size="15" /><br>
     <label for="entry2">Entry2</label>
      <input type="text" id="entry2" name="entry2" size="15"/><br>
     <label for="entry3">Entry3</label>
      <input type="text" id="entry3" name="entry3" size="15"/><br>
      <input type="hidden" name="id" value="1" /><br>
      <input type="hidden" name="table" value="table" /><br>
      <input type="submit" value="GO!" />
      <input type="button" value="later" onClick="hide1()"/>
    </form>
   </div><sub>1</sub>
  </td>
 </tr>
</tbody>

Upvotes: 0

Views: 2912

Answers (2)

dmi3y
dmi3y

Reputation: 3522

you could do something like this

 <tbody>
 <tr>
  <td style="cursor:pointer;">
   <div id="form1" style="display:none;">
    <form action="enter.php" method="post">
     <label for="entry1">Entry1</label>
      <input type="text" id="entry1" name="entry1" size="15" /><br>
     <label for="entry2">Entry2</label>
      <input type="text" id="entry2" name="entry2" size="15"/><br>
     <label for="entry3">Entry3</label>
      <input type="text" id="entry3" name="entry3" size="15"/><br>
      <input type="hidden" name="id" value="1" /><br>
      <input type="hidden" name="table" value="table" /><br>
      <input type="submit" value="GO!" />
      <input type="button" value="later" onClick="hide1()"/>
    </form>
   </div><sub onclick="click1()">1</sub>
  </td>
 </tr>
</tbody>

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77956

The button is a child of the td so both functions would be fired on the same click event.

Add this to hide1():

function hide1(e){
    document.getElementById('form1').style.display='none';
    e.stopPropagation();
}

This will prevent the event from bubbling up the DOM and triggering that td event.

You also need to pass the event in the click handler: onClick="hide1(event)"

Demo: http://jsfiddle.net/7PT8U/

Upvotes: 2

Related Questions