Question

I am having a little bit of difficulty passing a variable into a selector in prototype. I would like to be able to pass a variable into the select string, so that one function can work for many of the same kind.

At the moment, this is what I would basically like to do:

function myFunct(var)
{
  $(var + 'add_form').hide()  //so inde the brackets would be ('#product1 #add_form') for example.
}

Be able to pass 'var' into the function that would pass it to the selector, so that I can hide a pattern that is the same for many on the page.

Any ideas for a path to follow would be greatly appreciated.

Was it helpful?

Solution

You're on the right track! Couple things:

  1. var is a JavaScript keyword (source), don't use it to name a variable
  2. if you're querying an element by id (such as #add_form) you don't need to add any container element as you're doing
  3. If you're querying an element by class, you need to use the $$ function, not the $ function
  4. You need to iterate over the wrapped set to call your method
  5. whitespace is significant in css selectors, so make sure to include those in your selector construction to tell Prototype to search within your parent container:

    function myFunct(parent) {
      $$(parent + ' .add_form').invoke('hide')
    }
    
    myFunct('#someparent'); // hides .add_form inside #someparent
    

OTHER TIPS

That should work... just rename var to something else.

function myFunct(yourVar)
{

  $$('#' + yourVar + ' .add_form').each(function(s){ s.hide(); });  // yourVar being the id of the container element

}

I've put a '.' in front of add_form because you can't use multiple elements with same ID, make it a class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top