0

change event

$('.amount').on('change','input', function(){
        alert('hello!');
});

dynamicly created item:

<tr id="row{{$data['product_id']}}">
    <td><input type="checkbox" name="product[]" value="{{$data['product_id']}}"></td>
    <td>{{$data['product_id']}}</td>
    <td class="amount">{!! Form::input('number','qty',$data['qty'],['id'=>$data['product_id'],'min'=>'1','max'=>\App\Product::find($data['product_id'])->quantity,'required'=>'required'])!!}
    </td>
    <td>{{$data['stock']}}</td>
    <td id="rowprice{{$data['product_id']}}">{{$data['price']}} $</td>
    <td id="rowsum{{$data['product_id']}}">{{$data['qty']*$data['price']}} $</td>
</tr>

adding this item:

$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

        var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

        $.ajax({
            type: 'POST',
            dataType: 'JSON',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: $('#editOrderContent').attr('action'),
            data: data,
            success: function (html) {

               if (html.success) {
                    $('#summary').before(html.tdProduct);
                }
            }
        });

    });

So when I try to change the value of qty input with freshly created item, event doesn't trigger, but when I reload page, it does.

Johannes
  • 64,305
  • 18
  • 73
  • 130
Batmannn
  • 237
  • 4
  • 12
  • 1
    Could this be helpful? http://stackoverflow.com/questions/8650410/jquery-on-method-doesnt-see-new-elements – Amos Wong Mar 30 '17 at 21:02
  • uhhh no :C tried $('.amount').on('change',$( ":input" ), function(){ }, also tried with prevent default, still doesn't work((( – Batmannn Mar 30 '17 at 21:09

1 Answers1

3

When you bind to a class, ID, etc., jQuery is only able to bind to elements currently on the page. It can't see into the future. The common fix for this is to bind to the document. It's kind of hard to see what you actually want to bind to, but here's an example.

$(document).on('change','.amount input', function(){
        alert('hello!');
});
Gavin
  • 4,365
  • 1
  • 18
  • 27