最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

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/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

发布评论

评论列表(0)

  1. 暂无评论