开发者

Rails 3 forms question: How to create a "select" with "Add New ..." option?

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 ?


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/


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜