OdeToCode IC Logo

What’s Wrong With This Code (#16)

Tuesday, July 3, 2007

It’s been some time since the last WWTC, but Estelle Hertz is still cranking out software. This time Estelle was asked to write some JavaScript code for a web page with hundreds of textbox input controls (the page collects details for a life insurance policy). When a user double clicks on any textbox on the page, the textbox should reset itself to its initial value (the value in the control when the page first loaded).

Estelle has yet to experience all the slippery pitfalls in JavaScript development, and writes the following code:

<%@ Page Language="C#" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<
body>
    <form id="form1" runat="server">
        <div>
            <input id="Text1" value="default" type="text" />
            <%-- and so on for a 100 textbox controls --%>
        
</div>
    </form>
</
body>
</
html>

<
script type="text/javascript">

function
InputManager(input)
{
   
this._input = input;
   
this._initialValue = input.value;
   
this._input.ondblclick = this.resetToInitialValue;
}

InputManager.prototype.resetToInitialValue =
function()
{
    _input.value = _initialValue;
}

var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++)
{
    
if(inputs[i].type != "text")
        
continue;
        
    
var manager = new InputManager(inputs[i]);
}

</script>

Anyone spot a problem? Two problems? Three problems? Could there be possibly be more than three problems in the 20 line hunk of script?