0

I know this question has been asked but I can't wrap my head around how to implement it correctly in my use case.

End game is when an item is added to the cart by clicking the items add button, it triggers and ajax call passing the items id to a php function that adds it to the cart session (this works great).

On the ajax calls success it calls the function update_cart(), which builds new cart html and returns it. The div holding the cart html has its contents replaced by the new cart html contents (item qty price line items). This part works well also.

The new cart contents line items include name, the qty is displayed in an input, and the price.

The newly created line items qty input is not reacting the the onblur action (i think) due to the fact that it hasnt been bound to anything since it didnt exist on page load.

Can some amazing gentleman (or woman) and scholar help me understand how to bind the new inputs so I can call an ajax function to update the item qty when the field blurs?

My JS

$(document).ready(function () {

function update_cart() {

    var dataString = "";

    //alert (dataString);return false;
    $.ajax({
        type: "POST",
        dataType: "html",
        data: dataString,
        url: "/actions/updatecart.action.php",
        beforeSend: function() {
            $('#loader').show();
        },
        complete: function() {
            $('#loader').hide();
        },
        success: function(data) {

            $('#cart-items').hide().html(data).fadeIn( "slow");

        },
        error: function(data){
            $('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>Error Updating Cart</div>").slideDown( "fast");
        }
    });
};



$(function() {
    $("button[id^=add]").on("click", function(){
        var id = $( this ).data('id');

        var dataString = 'id='+ id;

         /* alert (dataString);return false; */
        $.ajax({
            type: "POST",
            dataType: "html",
            data: dataString,
            url: "/actions/add.action.php",
            beforeSend: function() {
                $('#loader').show();
            },
            complete: function() {
                $('#loader').hide();
            },
            success: update_cart ,
            error: function(data){
              //  $('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>Error Adding Item</div>").slideDown( "fast");
            }
        });
        return false;
    });
});

$(function() {
    $("input[id^=lineitem]").on("blur", function(){
        var id = $( this ).data('id');
        var qty = $( this ).val();

        var dataString = 'id='+ id + '&qty=' + qty;
        alert (dataString);return false;
        $.ajax({
            type: "POST",
            dataType: "html",
            data: dataString,
            url: "/actions/add.action.php",
            beforeSend: function() {
                $('#loader').show();
            },
            complete: function() {
                $('#loader').hide();
            },
            success: update_cart ,
            error: function(data){
                //  $('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>Error Updating Quanity</div>").slideDown( "fast");
            }
        });
        return false;
    });
  });
});

My Returned html and php foreach that creates it

foreach($_SESSION['basket']['items'] as $item){ ?>
<div class="cart-item">
    <div class="col-lg-8 col-md-8 np item"><?php echo $item['name']; ?></div>
    <div class="col-lg-2 col-md-2 np"><div class="input-group"><input data-id="<?php echo $item['id']; ?>" id="lineitem-<?php echo $item['id']; ?>" value="<?php echo $item['count']; ?>" type="text" class="form-control"></div></div>
    <div class="col-lg-2 col-md-2 np price"><?php echo $item['price']; ?></div>
</div>
<?php  } ?>

Thanks to anyone who can help me get my mind around how to do this. Everything was so smooth up until now.

MDS
  • 497
  • 1
  • 5
  • 16
  • bind the handler to a permanent asset that is an ancestor of your element using `on()`, and set the selector target argument . See event delegation part of `on()` docs and read up on how event delegation works – charlietfl May 31 '14 at 22:57
  • I understand that's the procedure, I just don't understand how to implement it. Can someone ELI5 to me – MDS May 31 '14 at 23:02
  • 1
    try changing `$("input[id^=lineitem]").on("blur", function(){` to `$("body").on("blur", "input[id^=lineitem]", function(){`. – Sean May 31 '14 at 23:04
  • Learn more about event delegation in the jQuery tutorial: http://learn.jquery.com/events/event-delegation/. – Felix Kling May 31 '14 at 23:07
  • YES! @Sean, thanks so much it works!. Could explain how that works? – MDS May 31 '14 at 23:07
  • 1
    Your jQuery script runs/binds on initial page load, when the DOM is ready. So any element that is added later, is not bound. So to bind dynamic elements you need to use `.on("blur")` on a parent element (ie. `document`, `body`, `#cart-items`) that is always there. So in your case by binding first to the `body` and then your element id. – Sean May 31 '14 at 23:11
  • @Sean can you answer the question so I can mark it accepted. – MDS May 31 '14 at 23:49
  • Since this was closed as a duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) it won't allow me to add a new answer. – Sean May 31 '14 at 23:52

1 Answers1

0

I think this is what you want:

...success: function(data) {
    $('#cart-items').hide().html(data).fadeIn( "slow");

    $(".cart-item .input-group input").bind("change",...function);

OR $(".cart-item .input-group input").on("change",...function); OR $(".cart-item .input-group input").change(...function);

}...