1

I am trying to make autofocus on select tag on page load. But I am not able to do that with autofocus tag.

 <select class="js-example-basic-single form-control" name="sel_bookID" id="sel_bookID" autofocus="autofocus" >
    @foreach ($arrayname as $data)                                       
        <option value="{{ $data->id }}">{{ $data->BookID }}</option>                                                      
    @endforeach
</select>

Here autofocus="autofocus" is not working. I refered to the question HTML select tag attribute similar to autofocus but can not get any appropriate solution. Can we do autofocus using javascript or jquery for select tag?

nischalinn
  • 1,133
  • 2
  • 12
  • 38
  • by focus do you mean that on page load drop down should get open? – Ahmad Jul 17 '18 at 09:44
  • No just focus on the select tag, then we can use tab for opening the dropdown. Thank You! – nischalinn Jul 17 '18 at 09:46
  • if that is the case you already have focus attribute set. The focus is there and you can change vales by pressing up or down arrow keys or press enter to show the drop down – Ahmad Jul 17 '18 at 09:48
  • Possible duplicate of [jquery focus on load](https://stackoverflow.com/questions/7814361/jquery-focus-on-load) – Ahmed Yousif Jul 17 '18 at 09:48
  • @Ahmad I already mentioned that autofocus property is not working. Thats why I posted my problem. Thank You!!! – nischalinn Jul 17 '18 at 09:49
  • its working for me – Ahmad Jul 17 '18 at 09:50
  • It should work, if you haven't used focus property in other elements. [Fiddle Example](https://jsfiddle.net/RajanPaneru/upac3gt4/1/). If you want to force, then you can use `$(document).ready` or `setTimeout` then `focus` method to make it work. – Rajan Jul 17 '18 at 09:53

1 Answers1

0

You can use the jQuery focus() method. When the DOM gets ready you need to set the focus on the select.

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

Or using pure javaScript:

document.addEventListener('DOMContentLoaded', function(){ 
    document.getElementById('sel_bookID').focus();
}, false);
Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34