PDA

View Full Version : Help with extracting filename from forms file upload field



SuperLes2006
01-18-2006, 10:28 AM
I'm trying to extract just the filename from a forms file upload field but just can't get it the way I want it.
Here's the code I'm using...


function extract(what)
{
if (what.indexOf('/') > -1)
answer = what.substring(what.lastIndexOf('/')+1,what.length);
else
answer = what.substring(what.lastIndexOf('\\')+1,what.length);
document.write(answer);
}



<form name="myform">
<input id="inpFile1" name="inpFile1" size="60" type="file">
<input style="height:23; color:#FF0000; font-weight:bold" type="button" value="Show Filename" onclick="extract(myform.inpFile1.value)">
</form>


Problem is that is writes the filename to a new white blank page in the top left corner.
How do I get it to write the filename to a spot on the current page? :confused:
Preferably right next to the Show Filename button.

alert(answer);
gives me a popup box with the filename but I don't want that.

jscheuer1
01-18-2006, 10:59 AM
The document.write() method, when executed after a page has loaded, overwrites the page. You need an element, possibly a span, with an id (you could use a text input with a name and access it through the form's element collection, if you want). Let's do it with a span:


function extract(what)
{
if (what.indexOf('/') > -1)
answer = what.substring(what.lastIndexOf('/')+1,what.length);
else
answer = what.substring(what.lastIndexOf('\\')+1,what.length);
document.getElementById('fname').innerHTML=answer;
}

and add the span in after the file button (keep your other HTML code too):


<input id="inpFile1" name="inpFile1" size="60" type="file"> <span id="fname"></span>

SuperLes2006
01-19-2006, 04:34 AM
That works!! Thanks :)

Could you also give me an example of how to put that filename
in a text box somewhere else on the page?

I really appreciate your help :D

jscheuer1
01-19-2006, 05:50 AM
Well, when you put it that way "a text box somewhere else on the page", I cannot be sure said text box will be part of the same form or part of any form. So, this is a good way to do that, under the circumstances:


function extract(what)
{
if (what.indexOf('/') > -1)
answer = what.substring(what.lastIndexOf('/')+1,what.length);
else
answer = what.substring(what.lastIndexOf('\\')+1,what.length);
document.getElementById('fname_txtbx').value=answer;
}


<input type="text" id="fname_txtbx">

Notes: This will work even if the text box is a part of a form. If it is a part of a form, say the 1st element in a form named 'form12', you can access its value like so:


document.forms['form12'][0].value