动态添加JS字段不保存到数据库

时间:2016-01-23 04:42:44

标签: javascript ruby-on-rails validation

我是Javascript的新手,正在开发一个Rails项目,通过使用以下代码双击页面,允许在页面上放置其他文本字段:

    <script type="text/javascript">
$(document).ready(function(){

    var counter = 2;

    $(document).dblclick(function () {

  if(counter>35){
            alert("You have exceeded the maximum allowable text fields");
            return false;
  }   

  var newTextBoxDiv = $(document.createElement('div'))
       .attr("id", 'TextBoxDiv' + counter);

  newTextBoxDiv.after().html('<input type="textbox" name="text' + counter + 
        '" id="document[text' + counter + ']" >');

  newTextBoxDiv.appendTo("#TextBoxesGroup");


  counter++;
     });

     $("#removeButton").click(function () {
  if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

  counter--;

        $("#TextBoxDiv" + counter).remove();

     });

     $("#getButtonValue").click(function () {

  var msg = '';
  for(i=1; i<counter; i++){
      msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
  }
        alert(msg);
     });
  });
</script>
</head><body>

<div id='TextBoxesGroup'>
  <div id="TextBoxDiv1">
    <input type='textbox' id='text1' name="document[text1]" >
  </div>
</div>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

除了动态创建的字段不保存到数据库之外,一切似乎都运行得很好。我确实检查了动态创建的字段是否为我的模型正确格式化,并且模型的参数允许其他字段。我对SO进行了一些研究,但似乎大多数答案都是针对其他用例 - 我确定我所缺少的内容非常小,但我很难在我的身上找到它。拥有。非常感谢方向!

修改

评论要求的扩展代码:

我的edit观点:

<%= form_for(@document) do |f| %>
  <% if @document.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@document.errors.count, "error") %> prohibited this document from being saved:</h2>

      <ul>
      <% @document.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
<script src="\assets\json2.min.js"></script>
<link href="\assets\jquery.signaturepad.css" rel="stylesheet">
<!-- <script type="text/javascript">
    $(window).load(function(){
        $('#instructionsModal').modal('show');
    });
</script> -->
<div class="center">
  <nav class="navbar navbar-default">
    <button class="btn btn-success btn-lg text-center navbutton" type="button" data-toggle="modal" data-target="#signatureModal">Complete and Sign</button>
  </nav>
</div>
<canvas>

</canvas>
  <div class="transfield">
    <%= f.label :signature %><br>
    <%= f.text_field :signature, :class => 'transfield' %>
  </div>
  <div class="transfield">
    <%= f.label :date %><br>
    <%= f.date_field :date, :class => 'transfield' %>
  </div>
  <div class="transfield">
    <%= f.label :text1 %><br>
    <%= f.text_area :text1, :class => 'transfield' %>
  </div>
  <div class="transfield">
    <%= f.label "Recipient" %><br>
    <%= f.text_field :recipient, :class => 'transfield' %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>



<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>-->
<script type="text/javascript">
$(document).ready(function(){

    var counter = 2;

    $(document).dblclick(function () {

  if(counter>35){
            alert("You have exceeded the maximum allowable text fields");
            return false;
  }   

  var newTextBoxDiv = $(document.createElement('div'))
       .attr("id", 'TextBoxDiv' + counter);

  newTextBoxDiv.after().html('<input type="textbox" name="text' + counter + 
        '" id="document[text' + counter + ']" >');

  newTextBoxDiv.appendTo("#TextBoxesGroup");


  counter++;
     });

     $("#removeButton").click(function () {
  if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

  counter--;

        $("#TextBoxDiv" + counter).remove();

     });

     $("#getButtonValue").click(function () {

  var msg = '';
  for(i=1; i<counter; i++){
      msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
  }
        alert(msg);
     });
  });
</script>
</head><body>

<div id='TextBoxesGroup'>
  <div id="TextBoxDiv1">
    <input type='textbox' id='text1' name="document[text1]" >
  </div>
</div>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

我的控制器:

class DocumentsController < ApplicationController
  before_filter :authenticate_user!, except: [:edit, :update]
  before_action :set_document, only: [:show, :edit, :update, :destroy]

  # GET /documents
  # GET /documents.json
  def index
    @documents = current_user.documents.order("created_at DESC").paginate(:page => params[:page], :per_page => 15)
  end

  # GET /documents/1
  # GET /documents/1.json
  def show
    respond_to do |format|
      format.html
      format.pdf do
      end 
     end  
  end

  # GET /documents/new
  def new
    if current_user.subscribed?
      @document = Document.new
      @document.user_id = current_user.id
      @available_templates = @current_user.templates.map{|tmplt| [tmplt.name, tmplt.id]}
    else 
      redirect_to new_charge_path
    end
  end
  # GET /documents/1/edit
  def edit
    #if @cms484.phy_sign.present?
    #redirect_to pages_error_path
  #else
    #@document = Document.find_by(authentication_token: params[:authentication_token], id: params[:id])
   # end
  end

  # POST /documents
  # POST /documents.json
  def create
    @document = @document = Document.new(document_params)
    @document.user_id = current_user.id

    respond_to do |format|
      if @document.save
        DocumentMailer.email(@document).deliver_later
        format.html { redirect_to documents_path, notice: 'Document was successfully created.' }
        format.json { render :show, status: :created, location: @document }
      else
        format.html { render :new }
        format.json { render json: @document.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /documents/1
  # PATCH/PUT /documents/1.json
  def update
    respond_to do |format|
      if @document.update(document_params)
        format.html { redirect_to @document, notice: 'Document was successfully updated.' }
        format.json { render :show, status: :ok, location: @document }
      else
        format.html { render :edit }
        format.json { render json: @document.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /documents/1
  # DELETE /documents/1.json
  def destroy
    @document.destroy
    respond_to do |format|
      format.html { redirect_to documents_url, notice: 'Document was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_document
      @document = Document.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def document_params
      params.require(:document).permit(:template_id, :recipient, :text2, :user_id, :signature, :date, :text1)
    end
end

我的模特:

class Document < ActiveRecord::Base

belongs_to :user

belongs_to :template

    before_create :add_token
        private
        def add_token
          begin
            self.authentication_token = SecureRandom.hex[0,10].upcase
          end while self.class.exists?(authentication_token: authentication_token)
        end
end

0 个答案:

没有答案