Prevent html input type file from showing open dialog

vbguyny picture vbguyny · Sep 23, 2012 · Viewed 9.6k times · Source

To make a long story short, I need to be able to prevent the default action from a input type="file". In other words I do not want to display the system's open dialog box when the user clicks on the "Browse" or "Choose File". I already have the replacement dialog working, but the system's open dialog box still appears.

Below is a sample of what I am currently trying to accomplish this. (PS: I am using Chrome 21)

<html>
<head>

<script type="text/javascript">
<!--

 file_onclick = function()
 {
  // Show custom dialog instead...
  event.stopPropagation(); // Doesn't work
  return false; // Neither does this
 };

//-->
</script>

</head>
<body>
  <input type="file" onclick="javascript: file_onclick();" />
</body>
</html>

Any ideas?

Answer

vbguyny picture vbguyny · Sep 24, 2012

Got it. I needed to disable the tag and then use the setTimeout method to re-enable it.

<html>
<head>

<script type="text/javascript">
<!--

 file_onclick = function(o)
 {
  // Show custom dialog instead...

  o.disabled = true;
  setTimeout(function() { o.disabled = false; }, 1);
 };

//-->
</script>

</head>
<body>
  <input type="file" onclick="javascript: file_onclick(this);" />
</body>
</html>