0

UPDATE BOTTOM OF THIS POST

I have a HTML table which looks like:

<table class="table table-hover" id="selectedProductsForContract">
    <thead>
        <tr>
            <th>Product</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="col-md-8">
                <p>Product name</p>
            </td>
            <td class="col-md-1">
                <input type="number" class="form-control" value="1">
            </td>
            <td class="col-md-2">
                <button type="button" class="btn btn-danger">
                    Remove
                </button>
            </td>
        </tr>

    </tbody>
</table>

Which I intend to dynamically populate with values from a listbox on selection. I'm generating the listbox using @Html.ListBox()

@Html.ListBox("allProducts", allProductsForSupplier, new { ID = "allProductsListbox", @class = "form-control", @onclick = "AddSelectedProductToTable()" })

The onclick event of the listbox looks like:

<script>
    function AddSelectedProductToTable() {

    var selectedProduct = $("#allProductsListbox option:selected").text();    

    $("#selectedProductsForContract").find('tbody')
        .append($('<tr>' +
            '<td class="col-md-8"><p>' + selectedProduct + '</p></td>' +
            '<td class="col-md-1"> <input type="number" class="form-control" value="1"> </td>' +
            '<td class="col-md-2">  <button type="button" class="btn btn-danger" onclick="RemoveSelectedProductFromTable(this)"> Remove </button > </td>' +
            '</tr>'));

    }
</script>

This does exactly what I want and produces the following: enter image description here

Once the table is populated, I need to POST the product name and amount selected back to the server.

I have tried several things but the closest I got was using the following:

<script type="text/javascript">
    $(function () {
      $("#btnInsert").click(function () {
        var itemlist = [];

        //get cell values, instead of the header text.
        $("table tr:not(:first)").each(function () {
            var tdlist = $(this).find("td");
            var Item = { ID: $(tdlist[0]).html(), Name: $(tdlist[1]).html() };
            itemlist.push(Item);
        })

        $.ajax({
            url: '@Url.Action("InsertValue", "Contract")', //
            dataType: "json",
            data: JSON.stringify({ itemlist: itemlist }),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                alert("success");
            },
            error: function (xhr) {
                alert("error");
            }
        });
      });
    });
</script>

Which POST's back to following controller:

[HttpPost]
public JsonResult InsertValue(Item[] itemlist)
{
    foreach (var i in itemlist)
    {
        //loop through the array and insert value into database.
    }
    return Json("Ok");
}

And produces the following output: enter image description here

I think there is a better way than what I am doing right now but am kind of lost here, I think parsing out the HTML with regex or string manipulation is not the answer here...

Can anyone suggest/guide me towards a decent way of doing what I want? If any questions please ask.

Kind regards!

UPDATE Thanks to @Adyson i have changed the AddSelectedProductToTable() to the following:

 $("table tr:not(:first)").each(function () {

        var tdlist = $(this).find("td");
        var input = $(tdlist[1]).find("input");

        var Item = { ID: $(tdlist[0]).text(), Name: $(input[0]).val() };
        itemlist.push(Item);   

    })

Where var input = $(tdlist[1]).find("input"); has been added and i needed to change the text() to val() of this part: Name: $(input[0]).val() to be able to retrieve the values.

THANK YOU SO MUCH ADyson!

3
  • 1
    rather than posting back snippets of HTML, just post back the values within the HTML...you can extract those with jQuery, e.g. using .text() to get the text in a td (instead of .html()), or .val() to get the value within the input field (which itself is within another td, of course). It's much easier to parse out the values client-side using jQuery which is designed for the purpose, than to try and to it on the server. And also you then don't send pointless extra HTML markup back and forth. Commented Feb 7, 2019 at 15:51
  • @ADyson, I had tried this but seems i didn't test it properly because this works indeed, at leasts for my first value (Id) but the second value is an empty string, which is logic since the second td tag has a input control inside it, so the td text value is "". How can i get the input control value inside my AddSelectedProductToTable() function? Thank you so far! You can post it as an answer if you want. Commented Feb 8, 2019 at 7:49
  • 1
    Something like $(tdlist[1]).find("input") should get your textbox (assuming it's inside index 1 of your row). Here's the documentation of the find() method. See if that helps. If you get it working I'll post everything as an answer Commented Feb 8, 2019 at 7:58

1 Answer 1

1

Rather than posting back snippets of HTML, just post back the values within the HTML.

You can extract those with jQuery, e.g. using .text() to get the text in a td (instead of .html()), or .val() to get the value within the input field (which itself is within another td, of course).

It's much easier to parse out the values client-side using jQuery which is designed for the purpose, than to try and to it on the server. And also you then don't send pointless extra HTML markup back and forth.

P.S. Something like var tb = $(tdlist[1]).find("input") should get your your textbox (assuming it's inside index 1 of your row). Then you can use tb.val() to extract the value entered into the box.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.