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;
}
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;
}
Share
Improve this question
edited Apr 3, 2012 at 19:17
John
asked Apr 3, 2012 at 18:56
JohnJohn
13.8k15 gold badges111 silver badges190 bronze badges
3
-
O.k. You are almost there, just return the
confirm
value, see my answer below. – gdoron Commented Apr 3, 2012 at 19:10 - @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 Commented Apr 3, 2012 at 19:15
- Colin, do not add unnecessary whitespace. – John Commented Apr 3, 2012 at 19:16
3 Answers
Reset to default 4Why 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.
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();}
}
}
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