0

I was trying to add a simple character count to a textarea and it took me a day to get it working. I wanted to post what I learned and ask for clarification from any helpful users out there.

Laravel was not running javascript until I uploaded the script into ProjectRoot/resources/js/app.js.

var maxLength = 100;
$('textarea').keyup(function() {
  var length = $(this).val().length;
  var length = maxLength-length;
  $('#chars').text(length);
});

Once the code is there I ran npm run dev (I have installed npm at this piont) and only THEN did the javascript run. The code is transferred into an app.js file in the ProjectRoot/public/js/app.js (which is a massive file where I couldn't find my code) directiory. I assume, and correct me if I'm wrong, this means npm run dev "converts" /"transfers" /"compiles" (what's the right word here?) the javascript to the laravel webmix system. This is where my knowledge and problem solving skills have puttered out.

Articles like this and this make it sound like I can just drop javascript into any xxx.blade.php file. Some other angles that did NOT work:

  • importing .js files in the public/js directiory. No luck.
  • <script src="{{asset('js/count.js')}}"></script> didn't work when I tried it in app.blade.php or the blade file with text area itself.
  • including *@section('script')* didn't work either.

I'm getting the classic Uncaught ReferenceError: $ is not defined in the chrome inspector console, but the countdown works so I I'm just not sure what's going on.

Can I run javascript inline in my xxx.blade.php with Laravel?

1 Answer 1

1

in your blade file, where you want to use your script:

@push('js')
<script>
var maxLength = 100;
$('textarea').keyup(function() {
  var length = $(this).val().length;
  var length = maxLength-length;
  $('#chars').text(length);
});
</script>
@endpush

and in your app.blade.php (your main blade where you include all the js/css files)

@stack('js')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You! Where would you have gone to look this up? The push command is used to "append to a collection". Why do I need to append it to a collection?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.