user544079
user544079

Reputation: 16629

Read value from a textbox

I have a simple textbox:

<input type="text" id="username" /><br />
<input type="button" id="Submit" value="Submit" onclick="Submit()" />

The function is defined as:

function Submit() {
   var username = document.getElementById("username").value;
   alert("Welcome " + username);
}

Why do I get the error below?

Cannot read property 'value' of null

Upvotes: 0

Views: 159

Answers (2)

scunliffe
scunliffe

Reputation: 63588

Internet Explorer does something very frustrating called "auto globals".

Every element on the page with a NAME attribute or an ID attribute is automatically assigned as a global object on the page.

You therefore unintentionally have a namespace collision because your function and the button are both called "Submit".

Try renaming your button (and/or add a doctype which tells newer versions of IE to stop doing this!)

Upvotes: 1

Danny Beckett
Danny Beckett

Reputation: 20748

Rename your function. Submit is likely a reserved word in your browser (though your code works fine in )

<input type="text" id="username" /><br />
<input type="button" id="Submit" value="Submit" onclick="mySubmit()" />
function mySubmit() {
   var username = document.getElementById("username").value;
   alert("Welcome " + username);
}

Failing that, double-check that the code you posted is actually the cause of the error.

Upvotes: 1

Related Questions