简体   繁体   中英

jQuery function works in console but not in code

The code below creates a search field and then attaches a focus event to it so the preset value disappears when users click in the input field. The .focus line works in the console but not in the code. How can I get it to work in the code?

<script type='text/javascript'>
jQuery( document ).ready(function( $ ) {
    jQuery('#site-nav').append("<div class='nav' style='width: 130px; margin-top: 15px;'><form     id='site-search' method='get' action='/search'><input id='search' name='search' class='textfield' tabindex='1' type='text' style='border-radius: 10px; height: 30px;' value='SEARCH'></form></div>")
});
jQuery("#search").focus(function(){$(this).val("");});
</script>

By the way, I have to spell out 'jQuery' because our app is configured that way to avoid conflicts Thanks. Blessings

Move the line inside the ready method:

jQuery( document ).ready(function( $ ) {
    jQuery('#site-nav').append("<div class='nav' style='width: 130px; margin-top: 15px;'><form     id='site-search' method='get' action='/search'><input id='search' name='search' class='textfield' tabindex='1' type='text' style='border-radius: 10px; height: 30px;' value='SEARCH'></form></div>");
    jQuery("#search").focus(function(){$(this).val("");});
});

Edit:

Keep in mind that the anonymous function in focus() always get triggered if the field gets the focus. So it will always be empty after this action

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