Home > Software engineering >  How can I add a browse button inside a text field?
How can I add a browse button inside a text field?

Time:01-05

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..

CodePudding user response:

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 >
  <input type="file" name="form" id="file-field">
  <hr />
  <textarea name="form" id="text-field" cols="30" rows="10" placeholder="Write here..."></textarea>
</div>

CodePudding user response:

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 >
  <input type="file" name="file" id="file">
  <hr />
  <textarea name="text" id="text" cols="30" rows="10" placeholder="Write here..."></textarea>
</div>

  •  Tags:  
  • Related