0

I have the following problems. I have 2 JQuery functions. One is for appending the content and the other one is for displaying the name of the selected file.

FUNCTION 1

<script> 
        jQuery( document ).ready(function( $ )
  {
   $("input[name=contribution_type]").on('change', function()
   {
    var value = this.value;

    $("#contribution").empty();

    if (value != 'none')
    {
        var div2 = 'content'
        $("#contribution").append(div2);
    }
   });

   });


       </script>

FUNCTION 2

 <script type="text/javascript">
    $(document).ready(function(name){
        $('input[type="file"]').change(function(e){
            var fileName = e.target.files[0].name;
            alert('The file "' + fileName +  '" has been selected.');
        });
    });
</script>

The var div2 = 'content' here is the whole form however it is too long so I did not include it.

Any ideas how on the second function for the file name will work in append()?

Thank you in advance!

Tibs
  • 735
  • 5
  • 16
Bobby
  • 29
  • 5
  • Yes. You'll have to reattach that listener to the form. It's bound to the original page, but not the form elements which get appended by jQuery. So you'll have to wrap that into an eventListener() method & recall that method after the form is appended. – Clomp Jan 15 '18 at 19:53
  • Good point Funk Forty Niner! The PHP tag has been removed. One could argue that the ` – Clomp Jan 15 '18 at 20:00
  • @Clomp Thank you, i will appreciate some help with the code :) – Bobby Jan 15 '18 at 20:02
  • Read this section on [event propagation](https://learn.jquery.com/events/event-delegation/#event-propagation). It will allow you to attach event handlers to dynamically-created elements -- which I think is what you are asking. You would do something like `$(document).on('change', 'input[type="file"]', ...)` in your 2nd script. – Mikey Jan 15 '18 at 20:05
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – showdev Jan 15 '18 at 20:16

1 Answers1

1

I've created a working demo for you to look at & test out at jsFiddle.

HTML:

<html>
    <body>
    <input type="text" id="contribution_type" placeholder="Enter some text here..." />
    <div id="contribution">
        <button id="button1" disabled>Click me. This button will change into a form upload field.</button>
    </div>
    </body>
</html>

jQuery:

$('#contribution_type').on('keyup', function() {
    $('#button1').removeAttr('disabled');
});

$('#contribution_type').on('blur', function() {
    let value = this.value;

    $("#contribution").empty();
    if (value !== 'none') {
        let div2 = '<input type="file"><div id="contribution">Attach a file. Then press this button:<button>Test</button></div>';
        $('#contribution').append(div2);
    }

    $('input[type="file"]').on('blur',function(e){
        if (e && e.target && e.target.files && e.target.files[0] && e.target.files[0].name) {
            let fileName = e.target.files[0].name;
            let output = 'The file "' + fileName +  '" has been selected.';
            console.log(output);
            alert(output);
        }
    });
});

Here is how this works:

  1. The change event doesn't work for <input> tags. It's for <select> elements. So it has to be switched to an event like: blur, click, keyUp, keyDown, keyPress, etc...
  2. This attribute is obsolete: type="text/javascript". We simply use <script> nowadays.
  3. New ES6 updates allow us to use the let keyword, which replaces the var keyword. It fixes problems with this and that, plus how they scope to JavaScript blocks... like function () {...} or if (){...} blocks.
  4. The upload form needed some object detection, so that it wouldn't thrown an error when the form pops up. That's what the e && e.target line is all about.
  5. The strict equality type checking operators, such as: !== and === are always preferred over loose equality operators, such as: != and ==. (The reason is that the JS code doesn't have to type cast to see if an integer 1 == a string '1'. That would be true, but 1 === '1' would be false.)
  6. You can replace $(document).ready with $().ready. See jQuery's API page on .ready for that short-cut.

I put in a console.log & an alert() method, so that you can see both examples. The console.log works better in loops than alerts. I wouldn't recommend 100+ looped alerts! ;-)

Hopefully, that'll point you in the right direction to get your upload form working. Good luck!

Clomp
  • 3,168
  • 2
  • 23
  • 36