6
votes

How do I prevent a form file input element from changing via the onclick DOM event when using the confirm() method?

In example I want to give a user the opportunity to not lose the value of a file input element by asking them if they wish to Ok|cancel, if they click cancel the file dialog window should not be displayed.

XHTML

<input name="post_file" onclick="images_change();" type="file" value="" />

JavaScript

function images_change()
{
 var answer = confirm('Okay or cancel, if you cancel no dialog window will be displayed.');

 if (answer)
 {
  answer = true;
  //previous item previews deleted here in a while loop.
 }
 else {answer = false;}

 return answer;
}
3
O.k. You are almost there, just return the confirm value, see my answer below. - gdoron is supporting Monica
@John If you need more from your answers than what you're currently asking -- "[...] I need to execute some other scripting on top of that." -- you should edit your question to include this. - Jonathan Lonowski
Colin, do not add unnecessary whitespace. - John

3 Answers

4
votes

Why not just inline it if you have the one file input?

HTML:

<input name="post_file" onclick="return check()" type="file" value="" />​

JavaScript:

function check() {
    return confirm('Okay or cancel, if you cancel no dialog window will be displayed.');
}​

jsFiddle example.

2
votes
document.getElementById('post_file').addEventListener('click',function(e) {images_click(e);},false);

function images_click(e)
{
  var answer = confirm('Ok or cancel?');

  if (answer)
  {
   //shows file selection dialog window.
  }
  else {e.preventDefault();}
 }
}
0
votes

You need to return the confirm result, and return the function result:

<input name="post_file" onclick=" return images_change();" type="file" value="" />​

function images_change() {
    return confirm('Okay or cancel, if you cancel no dialog window will be displayed.');
}

LIVE DEMO