使用 Javascript/JQuery/Rails 3 动态添加新行

Posted

技术标签:

【中文标题】使用 Javascript/JQuery/Rails 3 动态添加新行【英文标题】:Add new row dynamically with Javascript/JQuery/Rails 3 【发布时间】:2011-10-17 08:10:21 【问题描述】:

我正在构建一个包含日历的时间表表单,该日历使用户能够选择指定的日期并搜索项目。我有这个功能工作。我基本上是这样的:

一旦用户搜索他们的项目并按下加号按钮,即指定项目。在这种情况下是 Asda,然后用户将单击加号图标,该图标将创建一个新行并将其放入表“项目任务”中。你怎么能在 javascript/JQuery 中做到这一点。

很抱歉问了这么一个基本问题,但我仍在学习 Javascript/JQuery。

我目前有链接到project_project_tasks_path( project.id ) 的加号图标。这只是暂时的。

这是我目前所拥有的:

    <div class="left">
<table border="2"  id='projects' class='datatable'>
    <thead>
        <tr>
            <th>Number  &nbsp</th>
            <th>Name</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    <% @projects.each do |project| %>
        <tr>
            <td><%= project.project_number %></td>
            <td><%= project.project_name %></td>
            <td><%= link_to image_tag("icons/add.png"), project_project_tasks_path( project.id ), :remote => true %></td>
                <!-- link_to image_tag("icons/add.png"), tasklist_path(project.id), :as => "tasklist" -->
                        </tr>
    <%- end -%>
  </tbody>
</table>
</div>

<div class="right">
<b>Recently Viewed</b>
<table>
  <tr>
    <th>Project No.</th>
    <th>Project names</th>
    <th>Project Leader</th>
    <th></th>
  </tr>
  <tr>
    <td>123</td>
    <td>Test</td>
    <td>1</td>
    <td><%= link_to image_tag("icons/add.png") %></td>
  </tr>
</table>
</div>
</fieldset>

<fieldset>
    <b><center>Hours for Week commencing: <span id="startDate"><%= Date.today.beginning_of_week.strftime('%d/%m/%Y') %></span></center></b>
</fieldset>

<!-- Task list table -->
<div style="float: right; width: 300px; padding-left: 20px;">
  <fieldset>
    <b>Tasks for project</b>
    <ul id="task_list">

    </ul>
  </fieldset>
</div>

<!-- Hours list table -->
<fieldset>
    <table>
        <tr>
            <td>Leave</td>
            <td><input class="dayinput" type="text" name="Leave"></td>
        </t>
        <tr>
            <td>TOIL</td>
            <td><input class="dayinput" type="text" name="TOIL"></td>
        </tr>
        <tr>
            <td>Sick</td>
            <td><input class="dayinput" type="text" name="Sick"></td>
        </tr>
        <tr>
            <td>Total</td>
            <td><input id="total" class="total_low" type="text" value="0" disabled="">
        </tr>
    </table>
</fieldset>

编辑:

我创建了一个 task_list.js.erb,如下所示:

$('#task_list').html('');

<% @project.project_tasks.each do |task| %>
  $('#task_list').append('<ul><%= task.task_name %>');
<% end %>

项目负责人

 def index
    # check if we've got a project id parameter
    if( params[:project_id].nil? )
      @project = nil
    else
      @project = Project.find(params[:project_id])
    end

    if @project.nil?
      @project_tasks = ProjectTask.all
    else
      @project_tasks = Project.find(params[:project_id]).project_tasks
    end
    respond_to do |format|
      format.html # index.html.erb
      format.xml   render :xml => @project_tasks 
      format.js   # index.js.erb
    end
  end

根据所做的更改,它会输出:

JQuery Ui 自动完成代码:

$(function() 
    function log(message) 
        $( "<div/>" ).text( message ).prependTo("#log");
    
    $("#tags").autocomplete(
        source : function(request, response) 
            $.ajax(
                url : "/projectlist",
                dataType : "json",
                data : 
                    style : "full",
                    maxRows : 12,
                    term : request.term
                ,
                success : function(data) 
                    var results = [];
                    $.each(data, function(i, item) 
                        var itemToAdd = 
                            value : item,
                            label : item
                        ;
                        results.push(itemToAdd);
                    );
                    return response(results);
                
            );
        
    );
); 

【问题讨论】:

您需要在问题中指定您的项目是在添加客户端时保存到数据库中,还是在添加项目后用户提交表单。这将确定是否需要 ajax 请求。从分配项目编号的事实来看,这似乎暗示了一个 ajax 请求,但我只能猜测。 这应该让你开始,railscasts.com/episodes/197-nested-model-form-part-2 抱歉回复晚了,显示的项目来自一个名为项目的现有表。我试图让用户单击加号按钮,然后添加选定的项目并将其放入新行 【参考方案1】:

使用 jQuery 添加到 DOM 非常简单,使用 append 或 prepend 方法。

$('element_to_add_to').append('the html to append');
$('element_to_add_to').prepend('the html to append');

查看 jQuery 文档中的空方法。

另外,你有一些不好的标记。任务列表&lt;ul&gt; 没有&lt;li&gt;,而其中的表有一个额外的&lt;/tr&gt;

编辑:从您更新的帖子中,您似乎不仅要在表中插入一行,还要同时将数据保存到数据库中。在这种情况下,您需要对控制器方法进行 ajax 调用,该方法会将数据保存在数据库中。如果调用成功,则将更新后的行添加到表中。

$.ajax(
    type: "POST",
    url: "path to your route",
    data: "the data to send to your controller",
    success: function(data)
        // here is where you process the return value from your controller method
        // the data variable will hold the return value if the call is successful
        // you can make your controller return the html to be inserted in your table
        // and insert it from here or just return a status message and build and add
        // the html manually here.
    
);

【讨论】:

如果有帮助,我已经修改了我的问题 我想我明白你现在想做什么了。我添加到我的答案中。 我编辑了我的帖子,其中显示了我在 JQuery 自动完成中使用的类似 ajax 请求响应。我不知道如何让控制器返回 html。但是我不知道如何将它插入到表格中。

以上是关于使用 Javascript/JQuery/Rails 3 动态添加新行的主要内容,如果未能解决你的问题,请参考以下文章

在使用加载数据流步骤的猪中,使用(使用 PigStorage)和不使用它有啥区别?

今目标使用教程 今目标任务使用篇

Qt静态编译时使用OpenSSL有三种方式(不使用,动态使用,静态使用,默认是动态使用)

MySQL db 在按日期排序时使用“使用位置;使用临时;使用文件排序”

使用“使用严格”作为“使用强”的备份

Kettle java脚本组件的使用说明(简单使用升级使用)