JeffVader
JeffVader

Reputation: 702

Jquery - Dynamic table rows & DatePicker

I have a form with two fields, Date and Price.

The date field has a datepicker attached to it and that works fine.

I've added the option to add a new row to the table and again this works, with the option to delete the row.. But I have a couple of issues

  1. Whilst the datepicker works on each new datepicker field, the selected date is being posted back to the wrong field. If I delete a row then the datepicker posts back to the previous row.

  2. I want to use names like date[] and price[] so I can get the details from the form as an array. I think this isn't working due to the way jquery requires each field to have a unique name.

This is how my form is currently setup:

        <tr>
            <td><input id="date" class="datepick" name="date[]" type="text" /></td>
            <td><input type="text" name="price[]"></td>
            <td><a class="deleteRow"></a></td>
        </tr>

I've created a JFiddle here to show how far I've got upto now.

Thanks

Upvotes: 0

Views: 4580

Answers (1)

Uvaise
Uvaise

Reputation: 309

The problem is that you are using the same counter for the id of the new elements. So there could be two elements with same id at some point of time.

I have modified the code so that the ids will always be variable and also the names of the elements would be date[ ] which is the way you wanted.

HTML CODE FOR FIRST TR's DATE FIELD:

input id="date0" class="datepick" name="date[]" type="text" 

Javascript code:

$(document).ready(function(e) {
     var counter = 0;
     var idCnt = 1;

$(".datepick").datepicker({ dateFormat: "dd MM yy" });


$("#addrow").on("click", function () {

    counter = $('#myTable tr').length - 2;
    var newRow = $("<tr>");
    var cols = "";

    cols += '<td><input type="text" name="date[]" class="datepick dates" id="date"/></td>';
    cols += '<td><input type="text" name="price[]"/></td>';
    cols += '<td><input type="button" class="ibtnDel"  value="Delete"></td>';
    newRow.append(cols);
    console.log (cols);
    if (counter == 4) $('#addrow').attr('disabled', true).prop('value', "Done");
    $("table.order-list").append(newRow);
    counter++;

    $('.dates', newRow).each(function(i) {
        var newID = 'date' + idCnt;
        $(this).attr('id', newID);
        idCnt++;

        $(this).datepicker({ dateFormat: "dd MM yy" });

});

});

$("table.order-list").on("click", ".ibtnDel", function (event) {
    $(this).closest("tr").remove();
    counter -= 1;
    $('#addrow').attr('disabled', false).prop('value', "Add Row");
    $(".datepick").datepicker({ dateFormat: "dd MM yy" });

});
});

Upvotes: 1

Related Questions