1

I'm building a nested form in rails 3.1 and instead of pressing the "add" button i want to automaticly add an input field when typing text in an empty input field (just like making a question in facebook and adding poll options). But i also want to only add a field if there are characters typed in the field if the characters are removed the extra field should also be removed.

I am working with rails 3.1 and so jQuery and jquery-rails are included in my gem, i don't know coffee script yet.

    2 Answers 2

    5

    it's really easy. Just tap into the focus() event handler and add textboxes as you go along.

    I have created a simple demo for you here: http://jsfiddle.net/mcVnN/

    Warning: clicking any textbox will add a new textbox here. If you want to add new textbox ONLY on last textbox focus, just compare the id.

    If you have any doubts let me know.

    Cheers

    -- Sorry, did not read your full question, my mistake. I have put together some quick code http://jsfiddle.net/mcVnN/12/ again on jsfiddle, but you might want to change it to suit your needs.

    4
    • Wow thanks!! But can you also make it that it only adds a field if the text.size is bigger than 1 and also delete 1 input field when the field is blank again...?
      – Thijs
      CommentedJun 29, 2011 at 13:13
    • Thank you so much!! It's almost good... but i think i can get along with this example!! If i type some text in the second and and then in the third.. it works, bu when i remove the second one, the fourth will stay... but thanks so much already... now i have to implement it in my rails app!
      – Thijs
      CommentedJun 29, 2011 at 13:48
    • @Thijs : yes, it needs some fine tuning, I wrote it during my lunch break, will go home after work and see if I can improve it. You are welcome!CommentedJun 29, 2011 at 13:59
    • Wow in lunch time!! are you serious... hence your name!! Well it has to do with the toggle state, if an input field is added the "textAdded" var becomes true, but if you remove one character on the field above it the length is still > 0 but why is the "textAdded" var false again..?
      – Thijs
      CommentedJun 29, 2011 at 14:08
    0

    I was going through my answers a now and realized I had left you in the middle of nowhere.

    Took some time to completely re-write my answer - the above answer is a lot buggier, you are better off using the :last selector than manually trying to keep track of the last text box yourself.

    See my rewrite here: http://jsfiddle.net/mcVnN/29/

    I have also added a max text box count that you can change easily to configure how many textbox you want users to be able to add.

    Please replace the above code with this one, if you are using the above one at all.

    Thanks.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.