Laravel - javascript doesn't work inside @section blade (file input)

Viewed 355

I'm working on a Laravel project. I have an input for loading files and I'm basically trying to show the filename when the file is loaded (before sending the form).

I'm using this example https://codepen.io/hidde/pen/LyLmrG which works well on its own, but not inside my laravel views.

These are my files:

appHome.blade.php (basic layout)

<html>
...

<body class="font-body" >
     ...

     @yield('content')

     ...

    <script>
     var input = document.getElementById( 'file-upload' );
     var infoArea = document.getElementById( 'file-upload-filename' );
     input.addEventListener( 'change', showFileName );

     function showFileName( event ) {
        var input = event.srcElement;
        var fileName = input.files[0].name;
        infoArea.textContent = 'File name: ' + fileName;
        }
    </script>

</body>
</html>



import-form.blade.php

@extends('layouts.appHome')
@section('content')
   ...
   ...

   <form>
     <input type="file" id="file-upload" multiple required />
     <label for="file-upload">Upload file</label>
     <div id="file-upload-filename"></div>
   </form>

@endsection

I tried to console.log inside the js script or check if the filename variable exists and it all works, but I think it doesn't work when it adds the filename to the infoArea (infoArea.textContent).

Is this related to blade section/extends or js?

Thanks!

1 Answers

Try waiting for document ready state before you execute and javascript:

function ready(callbackFunc) {
  if (document.readyState !== 'loading') {
    // Document is already ready, call the callback directly
    callbackFunc();
  } else if (document.addEventListener) {
    // All modern browsers to register DOMContentLoaded
    document.addEventListener('DOMContentLoaded', callbackFunc);
  } else {
    // Old IE browsers
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState === 'complete') {
        callbackFunc();
      }
    });
  }
}

ready(function() {
    var input = document.getElementById( 'file-upload' );
    var infoArea = document.getElementById( 'file-upload-filename' );
    input.addEventListener( 'change', showFileName );
});

function showFileName( event ) {
    var input = event.srcElement;
    var fileName = input.files[0].name;
    infoArea.textContent = 'File name: ' + fileName;
}
Related