7

I have a modal form with material -UI TextField in react app, I have a default value, es. a file, and i would select only the name of the file no the extension when the element is load....

I did this code inside the tag TextField:

<textField 
    value={value}
    fullWidth
    autoFocus
    onFocus={event => {
    event.target.select()}} />

but this will select all text inside the textField. enter image description here How can I select only a part of the text? ex: if i have myfile.doc i would be selected only myfile like this enter image description here

Thanks

Angelotti
  • 673
  • 1
  • 6
  • 20
  • 1
    Please attach MCVE code https://stackoverflow.com/help/mcve – Alvin Theodora Jan 29 '19 at 08:17
  • `var filename = 'myfile.doc'; var filename_without_extension = filename.split('.')[0];` – Ionut Necula Jan 29 '19 at 08:20
  • but i have to show the extension inside the textFiled bat not select... – Angelotti Jan 29 '19 at 08:24
  • I think I answered ***but this will select all text inside the textField. How can I select only a part of the text? ex: if i have myfile.doc i would be selected only myfile***. If you have any another problems please listen to @AlvinTheodora advice in the first comment, which basically means you have to improve/update your question, or post another one. Your current code does not give us enough info to be able to help you. – Ionut Necula Jan 29 '19 at 08:26
  • Possible duplicate of [Selecting all text in HTML text input when clicked](https://stackoverflow.com/questions/4067469/selecting-all-text-in-html-text-input-when-clicked) – Alvin Theodora Jan 29 '19 at 08:35

2 Answers2

13

Use the setSelectionRange in combination with the lastIndexOf method to find the position of the last ..

class App extends React.Component {
  handleFocus = event => {
    event.preventDefault();
    const { target } = event;
    const extensionStarts = target.value.lastIndexOf('.');
    target.focus();
    target.setSelectionRange(0, extensionStarts);
  }
  
  render(){
    return (
      <input
        value={'myfile.doc'}
        onFocus={this.handleFocus}
      />
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
gazdagergo
  • 6,187
  • 1
  • 31
  • 45
1

I would use a split and take the first entry of the array.

text = "mydoc.doc";
console.log(text.split(".")[0]);
Suburbia91
  • 41
  • 1
  • But with this i will have in my textField only the name of the file, i need to have all name so "mydoc.doc" but only the part of the string mydoc it will be selected – Angelotti Jan 29 '19 at 08:30