0

I'm creating a react js application, and using HTML select dropdown. I want to focus on select when page load. below shows which code I'm using in select.

<select id="sel_bookID" autofocus> 
  <option value="binary"> 
    Binary Search 
  </option> 
  <option value="linear"> 
    Linear Search 
  </option> 
  <option value="interpolation"> 
    Interpolation Search 
  </option> 
</select> 

I'm also using below mention some StackOverflow solution but did not work.

//jquery
$(document).ready(function(){
    $('#sel_bookID').focus();
});

or

//javascript
document.addEventListener('DOMContentLoaded', function(){ 
    document.getElementById('sel_bookID').focus();
}, false);
sonu shaikh
  • 21
  • 2
  • 8

3 Answers3

0

This line:

<select autofocus>

should have an id attribute, like so:

<select autofocus id="selectElem">

JS:

window.onload = function () {
    document.getElementById('selectElem').focus();
};
Sarvesh Mahajan
  • 914
  • 7
  • 16
0

You need to add an id attribute to your select tag like this:

<select autofocus id="sel_bookID"> 
  <option value="binary"> 
    Binary Search 
  </option> 
  <option value="linear"> 
    Linear Search 
  </option> 
  <option value="interpolation"> 
    Interpolation Search 
  </option> 
</select> 

otherwise, your js script cannot find an element with id sel_bookID and returns undefined

Puupuls
  • 76
  • 12
0

This is react way using refs:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    this.myRef.current.focus();
  }

  render() {
    return (
      <div className="App">
        <select ref={this.myRef}>
          <option value="react">React</option>
          <option value="vue">Vue</option>
          <option value="angular">Angular</option>
        </select>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Refs and the DOM

CodeSandBox Example

If you prefer autofocus option you have to use autoFocus to make it work