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:
- 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...
- This attribute is obsolete:
type="text/javascript". We simply use <script> nowadays.
- 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.
- 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.
- 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.)
- 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!