views:

61

answers:

3

1) How to programatically (without writing the onclick="javascript:.." attribute) attach JavaScript (jQuery) function to the link below?

2) The simplest way to toggle hide/unhide after clicking on the Statement link? First click should display the DIV (unhide), the second click should hide it and so forth.

<a>Statement</a>
<div id="taxStatement">insert select statement dropdownbox</div>
+3  A: 

You can give the link a class, for example:

<a class="toggle" href="#">Statement</a>
<div id="taxStatement">insert select statement dropdownbox</div>

Then attach script on document.ready with .click() and .toggle() the element, like this:

$(function() {
  $("a.toggle").click(function(e) {
    $(this).next().toggle();
    e.preventDefault();
  });
});

You can initially hide the <div> in multiple ways, CSS:

#taxStatement { display: none; }

Or give it a class, e.g. class="toggleDiv" and hide them all the same way:

.toggleDiv { display: none; }

Or also in your document.ready, via script:

$(".toggleDiv").hide();

You can give it a try/experiment here.

Nick Craver
If I understand this right, it toggles the next div after the toggle link? If so, then this is great.
mare
@mare - Correct :)
Nick Craver
A: 
   var theDiv = $('#taxStatement');

   theDiv.hide();
// make the div hidden by default.

   theDiv.prev('a').click(function(){ theDiv.toggle(); });
// ^^^^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^^^^^^^^
// Attach the onclick                 hide & unhide.
//  assume the <a> is 
//  immediately before that <div>.
// It may be better to give an
//  id to that <a>.
KennyTM
`.closest()` only works to find parent elements :)
Nick Craver
+1  A: 

For Question 1 and 2, you'll want to use toggle:

$('a').toggle(
function () {
  // Unhide Statement
  $('#taxStatement').show();
},
function () {
  $('#taxStatement').hide();
});
JasCav