views:

143

answers:

1

Ok so this may be a dumb question (probably some syntax) but Google didn't tell me much about why this isn't working, so here goes.

I have a function append_..._fields that takes an arbitrary amount of arguments, first one being the id of what to add fields onto, and all following are just names for the fields. It's hacked together so there are probably a couple things I could improve. This function appears in an imported script type="text/javascript" tag in as generated by rails

append_widget_form_fields = function(a){
  var widget_el = $(arguments[0]);
  var new_li = Element.new("li", class : widget_el.id, id : widget_el.id+"_new");
  for (var field in arguments) {
    if (field == arguments[0]){} // ignore first arg.
    else { //inserts fields into <li>
      Element.insert(new_li, { bottom : get_input_box_from_field_name( field , widget_el.id )});
    }
  } // inserts <li> into widget
  Element.insert(widget_el, { bottom : new_li });
}

Either way, I don't see anything wrong with it in terms of how I define it. I did try adding a var in front of it all - didn't help. The way the function is called is:

<input type="button" value="Add Fields" onclick="append_widget_form_fields('some_widget_id', 'headline', 'author', 'link');"/>

Addendum question: JS should syntax error when something is wrong with the function, and not scrap the definition, correct?

+1  A: 

There are few problems here:

  1. append_widget_form_fields is undeclared. You should either declare it with var or change it into function declaration (i.e. function append_widget_form_fields(){...})

  2. There's no new method on Element in Prototype.js. However, Element can be called as constructor - new Element(...).

  3. Probably the main problem here is that you use class. class name is actually syntactically disallowed in object literals (in ES3, as it is part of "future reserved words"). You should either quote it - "class" - or change to "className" (which Prototype.js understands).

kangax
I'm not sure which of these that fixed it (also found some Element declarations without curly braces), but it's fixed now. Just wasn't used to JS coming from doing ruby straight for a month and a half. Thanks!
Olex Ponomarenko