John
John

Reputation: 13756

JavaScript: file input onclick prevent change if user cancels confirm()

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;
}

Upvotes: 6

Views: 4952

Answers (3)

John
John

Reputation: 13756

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();}
 }
}

Upvotes: 2

j08691
j08691

Reputation: 208012

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.

Upvotes: 4

gdoron
gdoron

Reputation: 150313

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

Upvotes: 0

Related Questions