3

I need to add a file browse button with file browse functionality inside the text field, in such a way that on click of the browse button, the selected filename(only one file needs to be selected) is displayed in the text field in which it sits.

The browse button must be INSIDE the text box. The file name that was browsed must be displayed in that text box..

Divya
  • 31
  • 3

2 Answers2

1

That's what you want. insertAtCursor function is from How to insert text into the textarea at the current cursor position?.

const textField = document.getElementById('text-field'),
  fileField = document.getElementById('file-field')

fileField.onchange = function(e) {
  // Copy to clipboard functionality
  navigator.clipboard.writeText(fileField.value);

  // Inserting text into textarea at the cursor position
  insertAtCursor(textField, fileField.value);
}

function insertAtCursor(myField, myValue) {
  //IE support
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  //MOZILLA and others
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos) +
      myValue +
      myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}
<div class="container">
  <input type="file" name="form" id="file-field">
  <hr />
  <textarea name="form" id="text-field" cols="30" rows="10" placeholder="Write here..."></textarea>
</div>
Oybek Odilov
  • 185
  • 9
1

You simply do this with an onchange event listener on the input[type=file] field. Then you take the value and paste it into the text field.

const textField = document.getElementById('text');
const fileField = document.getElementById('file');

fileField.onchange = function(e) {   
  textField.value = e.target.value;
}
<div class="container">
  <input type="file" name="file" id="file">
  <hr />
  <textarea name="text" id="text" cols="30" rows="10" placeholder="Write here..."></textarea>
</div>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79