Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use my own Jquery in Laravel 5

I am new at Laravel, I have to add a Jquery to my code how do I add this?

 $(document).ready(function(){
    $('#selectAll').on('click',function(){
        if ($(this).is(':checked')) {
            $('.chkbox').each(function(){
                this.checked = true;
            });
        }else{
            $('.chkbox').each(function(){
                this.checked = false;
            });
        }
    })
});

If I am creating a file named myjquery.js

  • Where do I add this file?
  • How should I link this? or any other method to add above code?
like image 449
Shweta Avatar asked Dec 14 '22 10:12

Shweta


1 Answers

You have to append it inside <script></script> tags and after including the jquery library.

If you include them both (your script and the jquery library) at the end of your page, right before the closing </body> tag, even better, because of usability reasons.

My advice:

Add this at the bottom of your main template:

.
.
.
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
        jQuery(document).ready(function() {
            @yield('postJquery');
        });
    </script>
    </body></html>

so that you ensure the jQuery library and subsequent javascript scripts are loaded at the end.

And then, add this in the view that needs your script and that extends your main template :

@section('postJquery')
    @parent
    $('#selectAll').on('click',function(){
        if ($(this).is(':checked')) {
            $('.chkbox').each(function(){
                this.checked = true;
            });
        }else{
            $('.chkbox').each(function(){
                this.checked = false;
            });
        }
    });
@endsection

So that your script is only included in the view that actually needs it. You can do this for any script you need. The @parent part is needed to prevent the overwriting of the postJquery section with a partial view casted by your a view already using the same section.

like image 104
Amarnasan Avatar answered Dec 25 '22 11:12

Amarnasan