Michael Horvilleur
Michael Horvilleur

Reputation: 149

Submit on enter with input type=file

I have a form with an input and the type is file. When I hit enter, I want the form to submit. But now if I hit enter and I am on the input with type=file, I get a pop-up with another finder window. How can I change what enter does when I am on the input with the type=file? (The onSubmit functions and everything else is fine. All the code needed to answer is below)

<input type="file" className="form-control" onChange={handleFile} ></input>

Upvotes: 1

Views: 137

Answers (1)

imvain2
imvain2

Reputation: 15847

One simple solution is simply hide the file input on change. Then in a keyup function check for 13 keycode and if the files length is > 0 so it only submits if the file has been selected.

let form = document.querySelector("form");
let file = form.querySelector("input[type='file']");

file.addEventListener("change",function(e){
   e.target.style.display = "none";
});

addEventListener("keyup", function(e) {  
  if (e.keyCode == 13 && file.files.length > 0) {
    form.submit();
  }
});
<form>
  <input type="file" className="form-control">

</form>

Upvotes: 3

Related Questions