简体   繁体   中英

jQuery click on button who have ajax callback doesn't work

I have a Drupal website and I create a form with a button who have an ajax callback, the callback works fine but now I want to throw a little javascript function when the use click on the submit button.

I don't want to create a separated file to use it with drupal just for this little function so I try to use the jquery click element :

$(document).on('click', '#commerce-checkout-coupon-ajax-wrapper button', function(){
    console.log("test");
});

or

$('#commerce-checkout-coupon-ajax-wrapper button').on('click', function(){
    console.log("test");
});

But this doesn't work, the log isn't triggered. All other event (hover, mouseenter, etc) works fine but with the click it's not working, the button launch the ajax call to his drupal function but it's not launching my javascript function.

What can I do ? The thing I want to do is removing something from the screen when we click on the button.

Edit: Here is the html of the form (generated by drupal)

<div id="edit-commerce-coupon--2" class="form-wrapper">
  <div class="form-item form-item-commerce-coupon-coupon-code form-type-textfield form-group"> 
  <label class="control-label" for="edit-commerce-coupon-coupon-code--2">Code Promo</label>
  <input class="form-control form-text" title="" data-toggle="tooltip" type="text" id="edit-commerce-coupon-coupon-code--2" name="commerce_coupon[coupon_code]" value="" size="60" maxlength="128" data-original-title="Saisir le code de votre coupon ici.">
  </div>
  <button type="submit" id="edit-commerce-coupon-coupon-add--2" name="coupon_add" value="Ajouter" class="btn btn-success form-submit icon-before ajax-processed"><span class="icon glyphicon glyphicon-plus" aria-hidden="true"> 
</span> Ajouter</button>

EDIT :

I also try another method which can work (I think), it's with the focusout :

 $('#commerce-checkout-coupon-ajax-wrapper .form-control.form-text').focusout(function (e) {
    console.log("test");
    $('.tooltip').remove();
});

The problem is similar, when I click on the button the input doesn't lost the focus, so the tooltip stay on the page

You can try a work around :

(function($){
  $(document).ready(function(){
     $('button[id*="edit-commerce-coupon-coupon-add"]').on('click', function(){
         console.log('test');
     });
  });

})(jQuery);

Also ensure you have attached correctly your js file to form

$form['#attached']['js'][] = 'pathtomyfile.js';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM