views:

38

answers:

1

Hello,

I want to hide and show some form in my page.

For each form theres a link, and i want that, when i click on this link, it hide and show the nearest form of the link.

My code looks like this :

    $$('.flagLink').each(function(s){
        $(s).observe('click', function(event) {
            // here i want to hide and show the nearest form
        });
    });

I've tried this :

    $$('.flagLink').each(function(s){
        $(s).observe('click', function(event) {
            $(s).next('form').toggle();
        });
    });

It works but, i would like to be more precise like :

    $$('.flagLink').each(function(s){
        $(s).observe('click', function(event) {
            $(s).next('.flagForm').toggle();
        });
    });

but the .flagForm selector doesnt work.

My code looks like this : flag

First I hide all the form in the page : $$('.flagForm').each(function(s){ $(s).hide(); }); Then i add the onclick event on them : $$('.flagLink').each(function(s){ $(s).observe('click', function(event) { $(s).next('.flagForm').toggle(); }); });

But with the .flagForm selector, it does not work

+1  A: 

To avoid hazardous DOM traversal, I recommend using element ids to bind a form to its link, like so:

<form id="myform1">...</form>
...
<a id="link_myform1" class="flagLink" href="#">...</a>

Then you can match the id of your A element against a regexp /link_(.*)/ to get the id of your form:

$$('.flagLink').invoke('observe', 'click', function(event) {
    if(event.element().id.match(/link_(.*)/)) $(RegExp.$1).toggle();
});

If you can't use this solution, then you have to be more specific about what you mean by "nearest". If the link and the form always have a common ancestor, then you can use a css selector to find the form wherever it is. Say the link and the form always have a common ancestor that is the grand-parent of the link, you can do:

$$('.flagLink').invoke('observe', 'click', function(event) {
    var form = event.element().up(2).select('form').first();
    if(form) form.toggle();
});
Alsciende