Owen
Owen

Reputation: 431

jQuery Ajax when using dynamic inputs

I have inputs which are dynamically created and I'm attempting to submit their value using onBlur. I'm still new to jQuery and AJAX, could someone explain to me why the function isn't being called?

Input:

<input type="text" class="quantity" onblur="updateQuantity()" name="quantity[]"/>

Script:

<script>
    function updateQuantity() {

        $(".quantity").blur(function(){
            var quantityValue = $(this).val();
            $.ajax({
                url: "pages/inventory_request_action.php",
                cache: false,
                type: 'POST',
                data: quantityValue,
                success: function(data) {
                    // do something
                }
            });
        });
    }
</script>

Upvotes: 0

Views: 78

Answers (1)

foxygen
foxygen

Reputation: 1388

You are registering the blur event listener twice (Once in the onblur attribute on your input element, and another in the updateQuantity function). So what's really happening is once the input is blurred, you aren't actually calling the ajax function, but are instead adding another event listener..

So, remove on onblur="updateQuantity()" from your input element since you are adding the same listener via jquery, and rearrange the logic in your updateQuantity function so that it only makes the ajax call, and doesn't worry about adding event listeners.

http://jsfiddle.net/xvtp3vrd/

HTML

<input type="text" class="quantity" name="quantity[]"/>

Javascript

function updateQuantity(quantityValue){

    alert('submitting quantityValue: ' + quantityValue);
    $.ajax({
        url: "pages/inventory_request_action.php",
        cache: false,
        type: 'POST',
        data: {quantityValue: quantityValue},
        success: function(data) {

        }
    });
}

$('.quantity').blur(function(){

    var val = $(this).val();
    updateQuantity(val);
});

Upvotes: 1

Related Questions