簡體   English   中英

使用Javascript / JQuery / Rails 3動態添加新行

[英]Add new row dynamically with Javascript/JQuery/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>

編輯:

我創建了一個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);
                }
            });
        }
    });
}); 

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM