SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2010
    Posts
    167
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Click Link Sets Focus on Input

    How can I make it so that when I click a link, my input box now has a cursor / focus set?

  2. #2
    SitePoint Zealot Gar onn's Avatar
    Join Date
    Feb 2011
    Location
    Belgium
    Posts
    130
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    <a href="javascript:document.getElementbyId('fieldId').focus()">focus the field</a>

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Here's a more flexible way to do that, without messing up your HTML code.

    Here's a link that references the field.

    Code html4strict:
    <a id="login" href="#username">Login</a>
    ...
    <input id="username" name="username">

    The above is guaranteed to at least partially work even when JavaScript is not available. Bonus!

    Attach an onclick event to the link:

    Code javascript:
    document.getElementById('login').onclick = function () {
        ...
    };

    and in the function, set the focus to the href target:

    Code javascript:
    ... = function () {
        var id = this.href.split('#')[1];
        document.getElementById(id).focus();
        return false;
    };
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •