Place cursor at the beginning of an input after event focus

2

I have a concern that I would like to share with you in order to find a solution.

I am using React for the implementation of a project and I need in one of my forms that when performing the autofocus of one of its inputs which already has an initial value, the cursor is located at the beginning ; that is, before the initial value. I show part of the code so that you have an idea of what I want to do.

Component builder

constructor(props) {
    super(props);
    this.state = {url: '.feeel.ai'};

    ...
}

In this.state = {url: '.myurl.com'}; I set the initial value of the input. The idea is that when you start writing, finish the input value in this way: urldeusuario.myurl.com .

Part of the render of the component where I want to do the work

<input type="text"
       className="name-field-container label-input"
       placeholder="myURL"
       ref="url"
       value={this.state.url}
       onChange={this.handleChange}
       onKeyUp={this.enterKeyPress}
       onFocus={this.onFocusValue}/>

With this.onFocusValue I invoke the function that should perform the job I want.

    
asked by Frank Corona 11.04.2017 в 15:47
source

1 answer

3

This is not a question of React.js, it's simple JavaScript. What you're looking for is achieved by setSelectionRange :

document.getElementById("prueba").addEventListener("click", onFocusValue);


function  onFocusValue () {
      this.setSelectionRange(0, 0);
    }
<input type="text" value="prueba" id="prueba">
    
answered by 11.04.2017 / 15:52
source