简体   繁体   中英

set focus() on textbox on form onload

I am trying to set focus on a textbox in a form that's a part of jQuery tree. Here is my code

$(document).ready(function() {

       $("#search").focus();

});

HTML:

 <div>
     <form action="search" method="post" name="frmSearch>
          <label for="search">Search:</label>
        <input type="text" name="search" id="search" />
        <input type="submit" name="button" value="Search" />
    </form>
</div>

When I click on Search tab in the tree, it won't set focus on the textbox. Can someone let me know what's wrong in the code?

You're focusing the textbox on page load, however as soon as you click anywhere else on the page (such as a tab), the focus will be removed from the textbox and given to whatever you just clicked.

Instead of focusing on page load, attach a click listener to your tab so that when it is clicked the search textbox gets focus. Since I haven't seen all your markup, I'm using #mySearchTab as a placeholder for the ID of your search tab:

$(document).ready(function() {
    $("#mySearchTab").on('click', function() {
       $('#search').focus();
    });
});

Also, don't forget to close your functions with a ) .

I'm not sure what your tree looks like but here's a working demo using jQuery tabs.

I made some modification in your js codes

http://jsfiddle.net/8CTqN/5

$(document).ready(function(){
    $(function(){
        $("#search2").focus();      
    });
});    

try following:

$(function(){
    $("input:first:text").focus();       
});

working fiddle here: http://jsfiddle.net/8CTqN/2/

tested on chrome

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM