Search code examples
javascriptjqueryinputfilenames

text input get filename on drop


I have an html form to write some filenames but its kinda lame to just write each filename in the form for everything that i will submit in the form. So i thought of a better idea which would be to just drag a filename of top of my text input and the text input's value changes to the name of the file. I know that i can specify file in the type attribute in the input but that's for uploading files. I dont want to upload anything. I only want to get the filename thats why i have a text input.

So, Im looking for either jQuery or Javascript solution to this problem. Unfortunately i dont have alot of code to share but i show an example of a form. I know this will be disliked because i dont share any javascript code but i don't even know where to begin and this is the only place i know to find out. So i'm sorry for that.

But here is the html form example

<form action="somefile.php" method="POST">
    <input type="text" name="mpqfile" placeholder="mpq filename">
    <input type="text" name="sqlfile" placeholder="sql filename">
    <input type="text" name="objfile" placeholder="obj filename">
    <input type="text" name="m2file" placeholder="m2 filename">
    <input type="text" name="skinfile" placeholder="skin filename">
    <input type="submit" value="send">
</form>

Solution

  • For each textbox you can define the drop zone around some parent DIV/Container.

    https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop

    You can access the file name using ev.dataTransfer.files[i].name in your drop handler. After you get the name of the file you can set the value of the respective textbox to the file name.

    document.getElementsByName("mpqfile").value = filename;