Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new row dynamically with 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:

enter image description here

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.

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

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

This is what I have so far:

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

Edited:

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

Project Controller

 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:

Inital Outlook if possible

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);
                }
            });
        }
    });
}); 
like image 501
Deej Avatar asked Aug 01 '11 10:08

Deej


1 Answers

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');

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

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

Edit: 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.
    }
});
like image 136
Craig M Avatar answered Nov 11 '22 15:11

Craig M