Search code examples
jquerymagentojgrowl

Magento/jQuery - Get input value AFTER user clicks


I'm using Magento 1.7.0.2 and jQuery 1.9.1 with jGrowl. What im trying to achieve is to get the quantity value of the user, and then displaying it as a jGrowl notification on the top right. jGrowl is just a way of displaying text using $.jGrowl("My Text Here"); Heres what I got so far:

HTML

    <div class="add-to-cart bottom">

    <input type="text" name="qty" id="qty" maxlength="12" value="500" title="Qty" onclick="$.jGrowl('500 Added To Cart');" class="input-text qty">
            <button type="button" title="Add to Cart" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span>Continue to cart</span></span></button>
        </div>

jQuery

    $('input#qty.input-text.qty').bind("keydown change", function(event){
    $.jGrowl(this.value);
});

It works but I the notifcation displays 3 different notifactions are the user types, if I type in 500 in the quantity box, it shows 5, 50, then 500 in seperate notifcations, is there a way to have it display AFTER the user click off the input field?

Thanks in advance


Solution

  • I'll provide 2 versions. You should bind your Javascript to an onclick or blur event instead of keydown:

    HTML:

    <div class="add-to-cart bottom">
        <input type="text" name="qty" id="qty" maxlength="12" value="500" title="Qty" class="input-text qty">
        <button type="button" title="Add to Cart" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span>Continue to cart</span></span>
        </button>
    </div>
    

    jQuery (when user focuses out from input box):

    jQuery('.add-to-cart.bottom .input-text').blur(function(){
        jQuery.jGrowl(jQuery(this).val());
    });
    

    OR

    jQuery (when user clicks button):

    jQuery('.add-to-cart.bottom .btn-cart').click(function(){
        jQuery.jGrowl(jQuery('.add-to-cart.bottom .qty').val());
    });
    

    Note it is best practice to avoid the usage of $ for jQuery in Magento due to Prototype & jQuery conflicts. Make sure you're running jQuery in noConflict() mode too.