5

I have this code:

.hidden_element {
  height: 1px;
  width: 1px;
  overflow: hidden;
}
<form action="">
  <label for="file">
    <button type="button" class="button red">Choose File</button>
  </label>
  <div class="hidden_element">
    <input type="file" name="video" id="file" />
  </div>
</form>

The problem is when I click choose file nothing happens.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sdfds dffdsf
  • 61
  • 1
  • 2
  • 7

3 Answers3

4

Change your button like <button type="button" onclick="document.getElementById('file').click()" class="button red">Choose File</button>

.hidden_element {
  height: 1px;
  width: 1px;
  overflow: hidden;
}
<form action="">
  <label for="file">
    <button type="button" onclick="document.getElementById('file').click()" class="button red">Choose File</button>
  </label>
  <div class="hidden_element">
    <input type="file" name="video" id="file" />
  </div>
</form>
Shijin TR
  • 7,516
  • 10
  • 55
  • 122
0

The label element applies to one input only: since it has one as a child (the button is an input element), it applies to it instead of the file-input as you hoped.

Just remove the button, maybe replace it with a span and style it as you wish, and clicking the label will open the file picker. No javascript needed! :)

.hidden_element {
  height: 1px;
  width: 1px;
  overflow: hidden;
}
.button {
  display: inline-block;
  box-sizing: border-box;
  border: 1px solid #aaa;
  background-image: linear-gradient(to bottom, #eee, #ccc);
  padding: 0.1em 0.2em;
  cursor: pointer;
}
<form action="">
  <label for="file">
    <span class="button red">Choose File</span>
  </label>
  <div class="hidden_element">
    <input type="file" name="video" id="file" />
  </div>
</form>
Elder
  • 41
  • 3
-1

I do not see the purpose of putting the button as a label. Either use a button or a submit to process your input (file upload). You should not hide your 'input file' tag. You really need two things for the user: the 'input file' tag to allow the user to choose the file he wants to upload and then a way to perform an action by submitting the form or perhaps an ajax call. However, since you are just learning this process, I recommend, just performing a simple submit and for you to write the code on the backend that will handle uploading the file. Here is a sample of my html code:

<form method="post" action="uploadFile.php">
 <input type="file" name="video" id="file" />
 <br /><br />
 <input type="submit" value="upload file">
</form>