Search code examples
javascriptruby-on-railsprototypejs

How can I dynamically add a select element to a form using Prototype & Rails?


I have generated the code for a select & its objects using Rails:

var insert_tag = '<select class="select medium" id="category_id" name="search[category_id]"><option value="-1">Select Category</option>
<option value="1">Boats and Cruisers</option>
<option value="2">Car Parts and Spares</option>
<option value="3">Caravans</option>
<option value="4">Coaches and Buses</option>
<option value="5">Commercial Parts</option>
<option value="6">Commercials</option>
<option value="7">Crash Repair Services</option></select>';

I have on JavaScript function which when called should insert this field into a blank div:

<div "form_field_a"></div>


$("form_field_a").insert(insert_tag);

But when this runs I just get this error:

content.toElement is not a function
[Break on this error] if (content && content.toElement) content = content.toElement(); 

I am new to JavaScript and have no idea why this does not work.


Solution

  • I don't know Prototype, but your div element is missing an id attribute (currently it is invalid HTML):

    <div id="form_field_a"></div>
    

    Then it seems to work: http://jsfiddle.net/KqVdf/1

    Also note that the value of insert_tag is one line without line breaks (got an error otherwise).