tags:

views:

55

answers:

3

Given the following javascript (jquery)

        $("#username").keyup(function () {
            selected.username = $("#username").val();

            var url = selected.protocol +
                (selected.prepend == true ? selected.username : selected.url) + "/" +
                (selected.prepend == true ? selected.url : selected.username);

            $("#identifier").val(url);
        });

This code basically reads a textbox (username), and when it is typed into, it reconstructs the url that is being displayed in another textbox (identifier).

This works fine - there are no problems with its functionality. However it feels 'slow' and 'sluggish'. Is there a cleaner/faster way to accomplish this task?

Here is the HTML as requested.

<fieldset class="identifier delta">
    <form action="/authenticate/openid" method="post" target="_top" >
        <input type="text" class="openid" id="identifier" name="identifier" readonly="readonly" />
        <input type='text' id='username' name='username' class="left" style='display: none;'/>
        <input type="submit" value="Login" style="height: 32px; padding-top: 1px; margin-right: 0px;" class="login right" />
    </form>
</fieldset>

The identifier textbox just has a value set based on the hyperlink anchor of a button.

+2  A: 

Other than saving from one less IF I don't see any optimization possible.

var url = selected.protocol + (selected.prepend == true ? selected.username + '/' + selected.url : selected.url + '/' + selected.username);
Ivo Sabev
+4  A: 

Cache your jquery objects...

var username = $('#username'),
    identifier = $('#identifier');

username.keyup(function () {
    selected.username = username.val();

    var url = selected.protocol +
        (selected.prepend == true ? selected.username : selected.url) + "/" +
        (selected.prepend == true ? selected.url : selected.username);

    identifier.val(url);
});

you are currently searching the dom twice on each key stroke.

Master Morality
Excellent! Thank you!
Stacey
+1  A: 

Yeah as the others have shown... the only optimization I can see is moving the objects outside the function:

var url = selected.protocol;
var iden = $("#identifier");
$("#username").keyup(function() {
 selected.username = $(this).val();
 iden.val( url + (selected.prepend == true ? selected.username + '/' + selected.url : selected.url + '/' + selected.username) );
})
fudgey