Reputation: 171399
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 ?
Upvotes: 3
Views: 2246
Reputation: 163268
To 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.net/tCBqA/
Upvotes: 6
Reputation: 2564
Checkout the following videos @ RailsCasts.com. 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.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
Upvotes: 2