Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript Detect Name of file chosen to attach to form, and alert if user selects wrong file
    text
    copied!<p>I have an HTML form with an input field to upload a file. I want the file chosen to match the correct file name desired (mcust.csv). If they select a different file, I want to trigger an error with JS.</p> <p>The form is shown below:</p> <pre><code>&lt;form name="upload-form" id="upload-form" action="upload-information.php" enctype="multipart/form-data" method="post"&gt; &lt;input type="file" name="dealers_csv" id="dealers_csv" required="required" data-message="Please attach the mcust.csv file."&gt; &lt;button type=\"submit\" name=\"Submit\" id=\"Submit\" class=\"csbutton-color upload-button\" style=\"margin-right:10px;\" &gt;Submit files&lt;/button&gt;&lt;img id=\"loader\" src=\"../images/loading.gif\" style=\"display:none;\"/&gt; &lt;/form&gt; </code></pre> <p>After the user attaches a file, I want to detect the name of the file (<strong>mcust.csv</strong>) and if the file name is NOT <strong>mcust.csv</strong>, I want to "do something" (show an error) using Javascript/jQuery BEFORE the form is submitted. </p> <p>Here's the JS :</p> <pre><code>$(document).ready(function () { $("#upload-form").validator({ position: 'top center', offset: [-12, 40], relative: true, accept: "csv", message: '&lt;div&gt;&lt;em&gt;&lt;/em&gt;&lt;/div&gt;' }) // make sure that mcust.csv is the attached file. If not, throw alert message $("input#dealers_csv").on("change", function() { var dealers = $("input#dealers_csv"); var arrfilepath = dealers.val().split("\\"); var filename = arrfilepath[arrfilepath.length - 1]; if (filename != "mcust.csv") { alert("Wrong file! Please select 'mcust.csv'"); dealers.val(''); } }); // make sure that morders.csv is the attached file. If not, throw alert message $("input#orders_csv").on("change", function() { var orders = $("input#orders_csv"); var arrfilepath2 = orders.val().split("\\"); var filename2 = arrfilepath2[arrfilepath2.length - 1]; if (filename2 != "morders.csv") { alert("Wrong file! Please select 'morders.csv'"); orders.val(''); } }); }); </code></pre> <p>EDIT: I've updated the above code to the working version. One question: Is there a way to show the data-message rather than an 'alert' if they attach the wrong file?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload