I am attempting to create a navigation bar with a button that toggles a div containing a search form. When the user clicks on the search button, I want the headerSearch
div to be displayed, and the navbarSearch
input to be automatically selected.
Although the search form is displayed, the input field is not automatically selected using the following code:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<nav class="navbar navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">
logo
</a>
<button class="btn btn-danger" type="button" data-toggle="collapse" data-target="#headerSearch" aria-controls="headerSearch" aria-expanded="false" onclick="selectSearchBox()">
Search
</button>
</div>
</nav>
<div class="collapse navbar-collapse bg-dark py-1" id="headerSearch">
<div class="container">
<form method="get" role="search" class="form-inline">
<input class="input form-control mr-1" id="navbarSearch" type="text" name="query">
<button class="btn btn-outline-light" type="submit">
Search
</button>
</form>
</div>
</div>
<script>
function selectSearchBox() {
document.getElementById("navbarSearch").select();
}
</script>