1

I want to iterate through my dynamically created table and create an array of elements Project Name, Client Name, and Field Rate at each index to populate and pass through a JSON object

Here is how my table looks:

        <table id="project-table" class="table table-striped table-hover">
        <thead>
        <tr>
            <th>Project Name</th>
            <th>Client Name</th>
            <th>Field Rate</th>
            <th>Delete Row</th>
        </tr>
        </thead>
        <tbody>
        <%--jquery will append our data here...     --%>
        </tbody>
    </table>
    <button type="button" onclick="projectTable()" class="btn btn-primary">Add Row</button>

function projectTable() {

projectRows = projectRows + 1;

var $tbody = $('#project-table').find('tbody');
var $id = $("");
var $tr = $("<tr>");

$id.append(
    "<hidden id='projectId'/>" +
    "<hidden id='projectVersion'/>"
);

$tr.append(
    "<td>" + "<input class='form-control' id='inputProjectName' placeholder='Project Name' type='text'>" + "</td>" +
    "<td>" + "<input class='form-control' id='inputClientName' placeholder='Client Name' type='text'>" + "</td>" +
    "<td>" + "<input class='form-control' id='inputRate' placeholder='Rate' type='text'></td>" +
    "<td>" + "<input type='button' value='Delete' onclick='deleteRow(this)'>" + "</td>");
$tbody.append($id);
$tbody.append($tr);}

projectTable() is called each time I click an Add new Row button. I want to be able to depending on how many rows have been created create an array containining the info from each of the rows like so:

            projectList: [
            {
                id: projectId,
                version: projectVersion,
                projectName: projectName,
                clientName: clientName,
                fieldRate: fieldRate
            }

but with multiple objects I have tried a few different for loops but they haven't worked for me.

2
  • What have you tried? A simple loop like $('#project-table').find('tr').each(...) loops through all rows and you just have to extract the data you need from the <td> elements!? Commented Aug 22, 2017 at 15:00
  • the problem I have ran into has been figuring out how to extract the data from only the first three as I do not want the Delete Button to be part of the extraction. Commented Aug 22, 2017 at 15:04

1 Answer 1

4

You could do it by selecting all the tr and then for each of those select the input elements to build your data.

Some issues in your current code:

  • You cannot have static id property values in your rows, as id values must be unique
  • The custom hidden element cannot be child of tbody. I don't see how you would need this element.

I have altered some other things in your code to make it more jQuery-like:

function projectTable() {
    $('#project-table>tbody').append(
        $("<tr>").append(
            $("<td>").append($("<input>").addClass("form-control")
                .attr({placeholder: "Project Name", type: "text"})),
            $("<td>").append($("<input>").addClass("form-control")
                .attr({placeholder: "Client Name", type: "text"})),
            $("<td>").append($("<input>").addClass("form-control")
                .attr({placeholder: "Rate", type: "text"})),
            $("<td>").append($("<input>").addClass("form-control delete")
                .attr({type: "button"}).val("Delete"))
        )
    );
}

$(document).on("click", ".delete", function () {
    $(this).closest("tr").remove();
});

$('#get').click(function () {
    var data = $.map($('#project-table>tbody>tr'), function (tr) {
        var $inp = $('input', tr);
        return {
            project: $inp.eq(0).val(),
            client: $inp.eq(1).val(),
            rate: $inp.eq(2).val(),
        };
    });
    $('#jsonout').text(JSON.stringify(data, null, 2));    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="project-table" class="table table-striped table-hover">
    <thead>
    <tr>
        <th>Project Name</th>
        <th>Client Name</th>
        <th>Field Rate</th>
        <th>Delete Row</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>
<button type="button" onclick="projectTable()" class="btn btn-primary">Add Row</button>
<button type="button" id="get" class="btn btn-primary">Get JSON</button>
<pre id="jsonout"></pre>

Sign up to request clarification or add additional context in comments.

3 Comments

I need the Id and Version for update purposes on the object. Is there a better way to handle this sort of thing?
Yes, you can put data- attributes on the tr element.
I ended up going a different route, but did find this to be a helpful point in starting. thank you for the assistance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.