使用Javascript / JQuery / Rails 3动态添加新行 [英] Add new row dynamically with Javascript/JQuery/Rails 3

查看:88
本文介绍了使用Javascript / JQuery / Rails 3动态添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a timesheet form that consists of a calendar which enables a user to select a specified date, and search for a project. I have this functionality working. What I basically have is this:

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

Once the user searches for their project and press the plus button, that specified project. Which in this instance is Asda the user would then click the plus icon which would create a new row and put it into the table 'task for project. How can you do this in Javascript/JQuery.

很抱歉问这个基本问题是什么,但我还在学习Javascript / JQuery。

Sorry for asking what may be seen as such a basic question, but am still learning Javascript/JQuery.

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

I currently have the plus icon linked to project_project_tasks_path( project.id ). This is just temporary.

这是我到目前为止:

    <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>

已编辑:

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

I have created a task_list.js.erb which is as followed:

$('#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

根据所做的更改,输出:

From the changes made, it outputs:

JQuery Ui自动完成代码:

JQuery Ui autocomplete code:

$(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);
                }
            });
        }
    });
}); 


推荐答案

使用jQuery添加到DOM非常简单追加或前置方法。

Adding to the DOM with jQuery is very simple with the append or prepend method.

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

查看jQuery文档中的空方法。

Check out the empty method in the jQuery docs as well.

另外,你有一些糟糕的标记。 task_list < ul> 没有< li> ,并且其中的表格有一个额外的< / tr>

Also, you have some bad markup. The task_list <ul> has no <li>'s and the table in there has an extra </tr>.

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

From your updated post, it seems like you want to not only insert a row in a table, but also save the data to your database at the same time. In that case, you'll want to make an ajax call to a controller method which will save the data in your DB. Then add the updated row to the table if the call is successful.

$.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.
    }
});

这篇关于使用Javascript / JQuery / Rails 3动态添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆