How select part of text in a Textfield on onFocus event with material-UI in React?
Solution 1
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>
Solution 2
I would use a split and take the first entry of the array.
text = "mydoc.doc";
console.log(text.split(".")[0]);
Angelotti
I am an enthusiastic and proactive person with an inquiring mind who can think “out of the box”. Working with passion and professionalism, I reach my goals. My diverse professional experiences are my strength – they have allowed me to gain customer-oriented, stress-resistant and problem-solving skills. My mother tongue is Italian, I speak English and French (Delf B1) fluently and started studying German. I consider myself a social person and love to be in company and spend my free time with friends. I love cooking, diving, traveling, reading, taking long walks in nature. My plans are to find a permanent job here in Switzerland and have a family.
Updated on June 04, 2022Comments
-
Angelotti almost 2 years
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. How can I select only a part of the text? ex: if i have myfile.doc i would be selected only myfile like this
Thanks
-
Angelotti over 5 yearsBut 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 over 5 yearsgazdagergo perfect thank you very much, that was exactly what I needed