javascript - Find if 'cancel' was clicked on file input -


i tried using hack described in various locations uses:

document.body.onfocus = checkoncancel(); 

an example:

var fileselectele = document.getelementbyid('fileinput');  fileselectele.onclick = charge;  function charge() {     document.body.onfocus = checkoncancel; }  function checkoncancel() {     alert("filename:" + fileselectele.value + "; length: " + fileselectele.value.length);     if(fileselectele.value.length == 0) alert('you clicked cancel!')     else alert('you selected file!');     document.body.onfocus = null; } 

is there wrong here? because fileselectedele.value returns previous execution value , not 1 selected user. expected behavior of input file? how resolve read actual file selected?

http://jsfiddle.net/smv9c/2/

you can reproduce error by:

step 1: selectfile - select file (and notice output)

step 2: selectfile - press cancel (and notice output)

one solution use onchange event of input.

var fileselectele = document.getelementbyid('fileinput');  fileselectele.onchange = function () {   if(fileselectele.value.length == 0) {     alert('you clicked cancel - ' + "filename:" + fileselectele.value + "; length: " + fileselectele.value.length);   } else {     alert('you selected file - ' + "filename:" + fileselectele.value + "; length: " + fileselectele.value.length);   } } 

this responds correctly changes in selected filename, can test here: http://jsfiddle.net/munderwood/6h2r7/1/

the potential difference in behaviour way trying it, if cancel right away, or twice in row, or select same file twice in row, event won't fire. however, every time filename changes, you'll detect correctly.

i don't know sure why original attempt didn't work, although best guess it's timing issue onfocus event firing asynchronously, , before input control's properties have finished updating.

update: determine user has selected every time close file dialog, if nothing has changed, timing issue can skirted adding brief delay between receiving focus again, , checking value of file input. instead of calling checkoncancel upon receiving focus, following version of charge causes called tenth of second later.

function charge() {   document.body.onfocus = function () { settimeout(checkoncancel, 100); }; } 

here's working version: http://jsfiddle.net/munderwood/6h2r7/2/.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -