Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use $ as well as jQuery

I have an opencart project where I have used $('#some-id') as well as jQuery('#some-id') which was working perfect, But after upgrading project from 1.5 to 2.1, its only accepting jQuery('#some-id') and throwing error for $('#some-id') as

TypeError: $(...) is null

following is my one of the hundred sample ajax function.

    $('#button-coupon').on('click', function() {
        $.ajax({
            url: 'index.php?route=total/coupon/coupon',
            type: 'post',

/*Here $ is not working jQuery works. Not just here, but in each line where $ is used its throwing error, untill & unless I replace it with jQuery.*/
            data: 'coupon=' + encodeURIComponent($('input[name=\'coupon\']').val()),
            dataType: 'json',
            success: function(json) {
                $('.alert').remove();
            }
        });
    });

Is there any way to get both of them work. I don't want to waste time in replacing $ with jQuery?

Following is the snapshot of error in firebug console.

If I change $('input[name=\'coupon\']') to jQuery('input[name=\'coupon\']') than it moves to some other line where $ is used. for example see below image.

next error after replacing $ with jQuery in above line.

I have tried to use latest as well as old versions of jQuery, but my problem still persists.

like image 996
Ahmed Syed Avatar asked Oct 31 '22 06:10

Ahmed Syed


1 Answers

Since you did not include any information about your code this is just a general hint, but probably worth diving into for you:

What is typically done when trying to prevent conflicts between different JS frameworks and libraries (all using the $ shortcut) is to encapsulate your own library or modules that way:

jQuery.noConflict();
(function($) {
    // your library or modules here
})(jQuery);

That way the identifier jQuery has to be specified only once, outside your own code, when the definition is "self calling" itself right away. Inside that block the jQuery library is now known under the shortcut $ again, but it does not collide with other usages of that shortcut outside that code block any more.

This is a compilation of hints about that topic: https://api.jquery.com/jquery.noconflict/

like image 89
arkascha Avatar answered Nov 01 '22 20:11

arkascha