Search code examples
javascriptruby-on-railsformsfrontendinputbox

Button to add an input box and accessing collections of inputs in controllers?


I'm a form noob and want to know how to create a collection of text-input boxes, along with a button that will allow users to add another input to this collection.

Can this be done purely with ruby and rails? If so, how do I access the individual inputs from the group when doing stuff in the controller? How do I identify each? How can I tell the size of the collection/how many inputs there are?

Any help would be appreciated, thanks!


Solution

  • A trivial, unstyled example of the front-end portion:

    HTML:

    <input type="button" id="addBtn" value="Add"/>
    <div id='inputs'>
    </div>
    

    Javascript with jQuery:

    var nextId = 0;
    
    $("#addBtn").on("click",function(){
        $("#inputs").append("<input type='text' id='text_"+nextId+"'/>");
        nextId++;
    });
    

    The inputs have unique, sequential ids. At any given time, the count is available either from nextId or $(".dynInput").length

    http://jsfiddle.net/5mHTh/1/