Set focus to search easily

Set focus to search easily

mbaasmbaas Posts: 67Questions: 24Answers: 1
edited January 2018 in DataTables 1.10

One thing I noticed recently is that it would be nice if the search-field on many of the Datatables I created could automically get focus on PageLoad. Now there is a lot of JS-Code around on the web t do this - but...
* it would be nice to have this as an optional feature in DT
* the HTML5-approach to this seems to be to set the "autofocus"-attribute on the control - and that calls for Datatables even louder (I suspect it would be need to be set early on).

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 63,530Questions: 1Answers: 10,473 Site admin
    Answer ✓
    var table = $('#myTable').DataTable();
    
    $('div.dataTables_filter input', table.table().container()).focus();
    

    would do it.

    Allan

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954
    edited January 2018 Answer ✓

    I wasn't able to get the autofucus attribute to work. I'm guessing because I added it after page load. I was able to use initComplete to set the focus using .focus():

        initComplete: function () {
          $('#example_filter label input').focus();
        }
    

    EDIT: Allan beat me to it with a better answer :smile:

    Kevin

  • mbaasmbaas Posts: 67Questions: 24Answers: 1

    Thanks to both of you. Actually I ended using mix of your answers: Allan's statement in the initComplete, as I was looking for something I could easily include in the "table-creation code". Kevin, thanks for confirmeing my suspicion re. autofocus.

This discussion has been closed.