I am trying to make it so that when the page loads, the user's mouse cursor is automatically in the input field, so he can start typing without having to move and click his mouse. However, it doesn't seem to work for me for some reason.
My HTML code:
<input type="text" placeholder="Search.." id="searchField">
<button type="submit" id="searchButton">Submit</button>
My JS/jQuery code:
$(document).ready(function() {
$("searchField").focus()
})
1.Need to add jQuery library
2.You forgot #
in jQuery code.(As it need to be selector)
<input type="text" placeholder="Search.." id="searchField">
<button type="submit" id="searchButton">Submit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function() {
$("#searchField").focus()
});
working snippet:-
$(document).ready(function() {
$("#searchField").focus()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Search.." id="searchField">
<button type="submit" id="searchButton">Submit</button>
HTML already has that functionality, with the autofocus
attribute. No need for JS.
Working snippet:
<input type="text" placeholder="Search.." id="searchField" autofocus>
<button type="submit" id="searchButton">Submit</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With