开发者

populating first field in form with cursor

I'm designing a series of forms. Is there a way I can mark a field to be populated by the browsers cursor (just like this pages loads wit开发者_StackOverflowh the cursor already in the title field above).

Thanks Giles


Use focus() function like this in Javascript. Put this code at the end of your HTML code, just before the </body> tag:

<script language="javascript" type="text/javascript">

document.getElementById("textboxid").focus();

</script>

Replace the textboxid with the ID of the <input> text box you are using in your form.


You can use Javascript to set your desired input focus:

Using JavaScript:

<script language="javascript" type="text/javascript">
    document.getElementById("xtpo_1").focus();
</script>

Using a JavaScript Library like Jquery:

<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $("#xtpo_1").focus();
    });
</script>


Even better, write an function

function autoFocus(x){

 document.getElementById(x).focus();

}

and put it in a separate javascript file called basic_functions.js or something.

Load that file at the top of your page in the header like this

<script type="text/javascript" src="basic_functions.js"></script>

In your body tag, call the function onload.

<body onload="focus('first_name')" >

Then create you input:

<input type='text' value='' name='first_name' id='first_name' />

That way you keep javascript functions out of your page and you can reuse the function on other pages. you can then put other basic functions like this in that file and include it in all pages where it is needed


In a HTML5 page, for browser supporting HTML5, you can do:

<input name="lorem" autofocus>

Vanilla Javascript:

<input id="lorem" name="lorem">
...
<script language="javascript" type="text/javascript">
  document.getElementById("lorem").focus();
</script>
</body>
</html>

jQuery:

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


Also you can do it in jQuery style and paste js-code anywhere:

HTML:

<input type="text" id="name"><br />
<input type="text" id="email">

Javascript:

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

Check it online: http://www.jsfiddle.net/4d5JG/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜