通过单击按钮导轨4添加文本区域 [英] Adding a text area by clicking a button-rails 4
问题描述
我在表单中列出了5个问题文本字段,供用户输入问题。我希望用户能够通过点击+按钮添加问题。
I have a list of 5 question text-fields in a form for a user to enter questions. I want a user to be able to add a question by clicking a "+" button.
我该怎么做?
我有一个样本:
<%= simple_form_for(@quiz, html: {class: 'form-vertical' }) do |f| %>
<%= render 'shared/error_messages_question' %>
<%= f.input_field :content, :rows => 3, :style => "width:80%", :placeholder => "enter your question." %>
<% end %>
推荐答案
设置<$ c $非常容易c> javascript / coffeescript ,
因为它是Rails让我们使用 coffeescript
,
Since it's Rails let's use coffeescript
,
您的 app / assets / javascripts
文件夹下的coffeescript文件名为 quizzes.js .coffee
,如果没有,你可以创建它。
You should have a coffeescript file under your app/assets/javascripts
folder named quizzes.js.coffee
, if not you can create it.
(同时确保你的 app / assets / javascripts里面/application.js
您需要该文件,或者您有 require_tree。
(Also make sure that inside your app/assets/javascripts/application.js
you require that file or you have require_tree .
现在里面文件你可以这样:
Now inside the file you can have something like this:
$ ->
template = "<textarea name='quiz[content][INDEX]'></textarea>"
index = $('textarea').length
$('#js-add-question-row').click ->
compiled_textarea = $(template.replace("INDEX", index))
$('#someform').append(compiled_textarea)
index = index + 1
你的html看起来应该是这样的:
And your html should look something like this:
<button id="js-add-question-row">+</button>
<form action="" method="" id="someform">
<textarea name="quiz[content][0]"></textarea>
</form>
我添加了一个javascript jsfiddle,告诉你它是如何工作的 http://jsfiddle.net/vjZ3g/
I added a javascript jsfiddle that shows you how it works http://jsfiddle.net/vjZ3g/
这篇关于通过单击按钮导轨4添加文本区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!