Jeff
Jeff

Reputation: 6130

JavaScript form focus, does my code look okay?

This morning I asked a pretty mundane question about my JS syntax, and someone suggested I use their code instead, so I went ahead with it because I know virtually Zero about JS.

Using my moderate PHP knowledge, I made a slight modification adding a second ID with an 'else if' statement (see below) and was just wondering if you folks who know more about JavaScript could tell me if it all looks good?

Or maybe you would do it differently altogether?

window.onload = formfocus;

function formfocus()
{
    var id_one;
    var id_two;

    id_one = document.getElementById( 'author' );
    id_two = document.getElementById( 's_primary' );

    if ( id_one )
    {
        id_one.focus();
        id_one.value = '';
    }
    else if ( id_two )
    {
        id_two.focus();
        id_two.value = '';
    }
}

EDIT: I am slightly concerned about my window.onload = formfocus(); ... but not really sure if there is any other way to accomplish what I want.

Upvotes: 0

Views: 139

Answers (3)

Michael Koval
Michael Koval

Reputation: 8377

While your code is functional, the following is much less verbose:

window.onload = function () {
    var id_one = document.getElementById("author");
    var id_two = document.getElementById("s_primary");

    // Original code...
}

Something to consider if you're planning on writing more Javascript.

Upvotes: 0

Chris
Chris

Reputation: 28064

It could definitely be more terse, especially if you use jquery. But assuming you want to stick to plain old javascript, I'd at least change the following:

var id_one;
var id_two;

id_one = document.getElementById( 'author' );
id_two = document.getElementById( 's_primary' );

to

var id_one = document.getElementById( 'author' );
var id_two = document.getElementById( 's_primary' );

Also, it's fairly standard practice not to surround function arguments with spaces, but I suppose that's a style issue that shouldn't be debated here.

Upvotes: 3

Cleiton
Cleiton

Reputation: 18133

It looks so good, it is readable and easy to understand.

Just to increase your knowledge about javascript syntax, you could do something like it too:

function formfocus()
{
    var id_one;
    var id_two;

    id_one = document.getElementById( 'author' );
    id_two = document.getElementById( 's_primary' );

    with(id_one || id_two)
    {
        focus();
        value = '';
    }
}

*ps, this example is ugly I know (but I love use "with" LOL).

Upvotes: -1

Related Questions