Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why file open dialog opens twice on clicking the button in FireFox

I have a file <input> field and a <span> decorates the input field:

<span class="span5 btn btn-primary btn-file" id="chose_files_btn" onclick="filechose_button.click()">chose files
    <input id="filechose_button" type="file" name="fileData" size="1" style="display: none"/>
</span>

While the behavior of this is as I suppose in Chrome and Safari, FireFox opens two file input dialogs on clicking the button(span).

Why could happen so?

I assume, that file input field is invisible and only access to it is through the span with a button behavior.

Update:

if I put the <input> outside of <span> it behaves normally.

 <span class="span5 btn btn-primary btn-file" id="chose_files_btn" onclick="filechose_button.click()">chose files</span>
 <input id="filechose_button" type="file" name="fileData" size="1" style="display: none"/>

JSFiddle

but why on inside position it does not?

like image 994
static Avatar asked Apr 30 '13 05:04

static


2 Answers

It is because of some kind of event propagation mess

<span class="span5 btn btn-primary btn-file" id="chose_files_btn" onclick="doOpen(event)">chose files
    <input id="filechose_button" type="file" name="fileData" size="1" style="display: none"/>
</span>

And

function doOpen(event){
    event = event || window.event;
    if(event.target.id != 'filechose_button'){
        filechose_button.click();
    }
}

Demo: Fiddle

like image 96
Arun P Johny Avatar answered Oct 07 '22 09:10

Arun P Johny


It is because of event propagation. When you click on the span, click event is raised and in the click handler you have called click on input type="file" so it is calling twice.

If you will try following code it would not raise propagated event.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">
 $(document).ready(function(){
 $("#chose_files_btn").click(function(event){

 filechose_button.click();
}); 
$("#filechose_button").click(function(event){
    event.stopPropagation();
});
});
</script>

<span class="span5 btn btn-primary btn-file" id="chose_files_btn">chose files
<input id="filechose_button" type="file" name="fileData" size="1" style="display:     none"/>
</span>

For more information visit this link

You should play with this to get more understanding on event propagation.

like image 7
Jenish Rabadiya Avatar answered Oct 07 '22 07:10

Jenish Rabadiya