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

Dav*_*vid 5 javascript forms jquery ruby-on-rails ruby-on-rails-3

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

在此输入图像描述

一旦用户搜索他们的项目并按加号按钮,即指定的项目.在这个实例中,Asda用户将点击加号图标,该图标将创建一个新行并将其放入表格的项目任务中.你怎么能在Javascript/JQuery中做到这一点.

很抱歉询问可能被视为这样一个基本问题,但我还在学习Javascript/JQuery.

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

这是我到目前为止:

    <div class="left">
<table border="2" width="" 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>
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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

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

项目管理员

 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
Run Code Online (Sandbox Code Playgroud)

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

如果可能,初始展望

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);
                }
            });
        }
    });
}); 
Run Code Online (Sandbox Code Playgroud)

Cra*_*g M 8

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

$('element_to_add_to').append('the html to append');
$('element_to_add_to').prepend('the html to append');
Run Code Online (Sandbox Code Playgroud)

查看jQuery文档中的空方法.

此外,你有一些不好的标记.task_list <ul>没有<li>,并且那里的表有一个额外的</tr>.

编辑:从您更新的帖子中,您似乎不仅要在表中插入行,还要同时将数据保存到数据库中.在这种情况下,您需要对控制器方法进行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.
    }
});
Run Code Online (Sandbox Code Playgroud)