I would like to create a select
box with currently existing brands (e.g. Sony, Panasonic, and so on). In addition, I would like to have Add New Brand
option, such that when user clicks this option, a new text field appears.
Is there any helper methods in Rails 3 that do such thing, or I need to implement this myself using Javascript ?
I would like to create a select
box with currently existing brands (e.g. Sony, Panasonic, and so on). In addition, I would like to have Add New Brand
option, such that when user clicks this option, a new text field appears.
Is there any helper methods in Rails 3 that do such thing, or I need to implement this myself using Javascript ?
Share edited Dec 11, 2010 at 22:00 Jacob Relkin 163k33 gold badges351 silver badges321 bronze badges asked Dec 11, 2010 at 21:35 Misha MoroshkoMisha Moroshko 172k230 gold badges520 silver badges760 bronze badges2 Answers
Reset to default 6To my knowledge there is no such helper method.
Here's how I would do it in JS:
document.getElementById('someSelectBox').onchange = function() {
if(this.selectedIndex != this.options.length -1) return;
var new_name = prompt('Please enter a name');
if(!new_name.length) return;
var textbox = document.createElement('input');
textbox.value = new_name;
this.parentNode.appendChild(textbox); //parentNode is presumably the form
}
Working example: http://jsfiddle/tCBqA/
Checkout the following videos @ RailsCasts.. Ryan Bates explains how to create a nested form and then use jQuery or Prototype to add and remove fields dynamically. It isn't a perfect match for you question but should get you headed in the right direction. If you get some code that works well consider posting it back on this question for everyone to see.
http://railscasts./episodes/196-nested-model-form-part-1
http://railscasts./episodes/197-nested-model-form-part-2