-1

I have to create a button. If the user click the said button, he is prompted to choose a file to upload. After choosing the file, using Javascript or JQuery, i have to fill a form and submit it so the file can be uploaded.

The problem is that i cannot use the usual html

<input type="file" name="xml" class="custom-upload" id="custom-upload"/>

Is there anyway on how to do this? I have searched thoroughly and all the possible answears seem overly complicated so i thought i was missing a more essential solution.

  • 1
    What exactly do you want? – Starx Feb 27 '13 at 17:08
  • 2
    What do you mean by _"i cannot use the usual html"_? – magnattic Feb 27 '13 at 17:08
  • Related : http://stackoverflow.com/questions/793014/jquery-trigger-file-input **or** http://stackoverflow.com/questions/5291942/how-to-trigger-a-input-type-file-element-using-jquery **or** http://stackoverflow.com/questions/4502612/trigger-file-upload-dialog-using-javascript-jquery **and** https://www.google.ca/search?num=100&newwindow=1&q=jquery+trigger+input+type+file+site%3Astackoverflow.com – Milche Patern Feb 27 '13 at 17:18
  • sorry, i forgot to edit my code correctly, edited it right away – Rafael El Bundas Fernandez Feb 27 '13 at 17:18

1 Answers1

1

You can create an image showing a image of a button instead. Then on click of that button, you can trigger the click event of the real file input.

<img id="imageButton" src="soure/to/imagebutton.jpg" />
<input type="file" id="fileImageButton" style="display: none; " />

And a little jQuery to do the trick

$("#imageButton").on('click', function() {
    $("#fileImageButton").trigger('click');
});

Or, vanilla javascript

document.getElementById('imageButton').addEventListener('click', function() {
  fileinput = document.getElementById('fileImageButton');

  if (document.createEvent) {
    var evt = document.createEvent("MouseEvents")
    evt.initMouseEvent("click", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
    fileinput.dispatchEvent(evt);
  } else {
    element.fireEvent("onclick"); //For IE
  }
});
Starx
  • 77,474
  • 47
  • 185
  • 261
  • Y U USE JQUERY?!? I know the OP had it as a tag... but there is no need to use it... :-( – Naftali Feb 27 '13 at 17:13
  • @Neal, Common dont be sad, I will add a JS version too. – Starx Feb 27 '13 at 17:13
  • That allows me to trigger the click on the input, that is true. it is one of the solutions i have tried to use. but how can I "wait" for the user to choose his file and after that change the form field and make the submit to my server? – Rafael El Bundas Fernandez Feb 27 '13 at 17:21
  • I think so @Starx :-D – Naftali Feb 27 '13 at 17:26
  • @RafaelElBundasFernandez, When the file is browsed, you can just submit. It is be submitted to the required page. If that was, what you asked. – Starx Feb 27 '13 at 17:39