Bandi Su
Bandi Su

Reputation: 125

JQuery won't add first row

I'm new in JQuery and I wanted to add row table with JQuery but my code won't add first row when the table has no row (If I already had a row it was work). So, what's wrong with my code?

jQuery(function () {
  var i = -1;
  $('input[name=barcode]').keydown(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code==13) {
        var idx = i+1;
        var $this = $(this);
        var kode = $(".barcode").val();
        $.get('engine.php?kode='+kode+'&button=getDataBarang' , function(data) {
            var arrayObj = JSON.parse(data);
            var k=0; 
            var arr = [];
            $.each(arrayObj , function(key, value) {
                arr[k] = value;
                k++;
            });
            var newRow = $("<tr align='center'><td class='kode_barang'>" + $this.val() + "</td>" +
            "<td> "+arr[0]+" </td> <td> "+arr[1]+" </td> "+
            " <td><input class='harga' required type='text' name='harga["+(idx)+"]' size='10' maxlength='9' pattern='.{1,9}' value='"+arr[2]+"'> </td> <td class='stok'> "+arr[3]+" </td>"+
            " <td> <input class='jumlah' required type='text' name='jumlah["+(idx)+"]' size='3' maxlength='4' pattern='.{1,4}' value='1'> </td> "+
            "<td><input type='text' name='sub["+(idx)+"]' size='10' value='"+arr[2]+"' disabled></td>"+
            "<td><a href='#' class='remove'><font color='0404B4'>Batal</font></a></td>"+
            "<input type='hidden' name='kode[]' value='"+kode+"'></tr>");
            $('#tab > tbody > tr').eq(idx).after(newRow);
            alert(idx);
            //add total
            var total = 0;
            $('.harga').each(function () {
                var $this = $(this);
                var harga = parseInt($this.val());
                var index = $(this).prop('name').match(/\[(.*?)\]/)[1];
                var jumlah = $('input[name^=jumlah]').eq(index).val();
                $('input[name^=sub]').eq(index).val(jumlah*$(this).val());
                total += jumlah * harga;
            })
            $('.total').text(total);
            $('.barcode').val('');
        });
        return false;
    }
  });
});

Upvotes: 0

Views: 53

Answers (1)

jfriend00
jfriend00

Reputation: 707298

It isn't clear where exactly you want the new row added, but if all you're trying to do is solve the problem of adding the new row when there are not yet any rows, you can change this:

$('#tab > tbody > tr').eq(idx).after(newRow);

to this:

var row = $('#tab > tbody > tr').eq(idx);
if (row.length) {
    row.after(newRow);
} else {
    $('#tab > tbody').append(newRow);
}

If you always want to just add a row to the end of the table, then you can just always use:

$('#tab > tbody').append(newRow);

Upvotes: 1

Related Questions