adding a text input field through js or jQuery when clicking on another input field in rails 3

前提是你 提交于 2019-12-11 05:58:46

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6520602/adding-a-text-input-field-through-js-or-jquery-when-clicking-on-another-input-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!