Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 783
John Avatar asked Apr 03 '12 18:04

John


1 Answers

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.

like image 191
j08691 Avatar answered Sep 29 '22 17:09

j08691