Ad

Dynamic Inputs Undefined Value Issue?

I get an undefined value when console.log($('#mat_code_' + counter - 1).val()); and the inputs are still empty.

Here is my code :

$('#m_table').on('click', '.check', function() {
                var table = $('#m_table').DataTable();
                //var limit = 2;
                if ($("input[name='check']:checked").length > counter) {
                    this.checked = false;
                    $('#mat_code_' + counter - 1).val(table.row(this.closest('tr')).data()['mat_code']);
                    $('#mat_designation_' + counter - 1).val(table.row(this.closest('tr')).data()['mat_designation']);
                }
                console.log($('#mat_code_' + counter - 1).val());
            });

Inputs are generated like this :

var counter = 0;

    $("#addrow").on("click", function() {
                    var newRow = $("<tr>");
                    var cols = "";

                    //cols += '<td><input type="text" required="required" class="form-control" name="' + counter + '"/></td>';
                    cols += '<td><input type="text" required="required" class="form-control" name="mat_code_' + counter + '" id="mat_code_' + counter + '"/></td>';
                    cols += '<td><input type="text" required="required" class="form-control" name="mat_designation_' + counter + '" id="mat_designation_' + counter + '"/></td>';
                    cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger" value="Supprimer"></td>';
                    newRow.append(cols);
                    $("table.order-list").append(newRow);
                    counter++;
                    $("#nb_mat").val(counter);
                    $('#action').attr("disabled", false);
                });
Ad

Answer

Try using parenthesis to perform the arithmetic operation before the string concatenation:

$('#mat_code_' + (counter - 1))
Ad
source: stackoverflow.com
Ad