Reputation: 101
in the following piece of code i want to access input text box value using your id. but it's throwing an object error.
<HTML>
<HEAD>
<script>
function test()
{
var a1 = document.getElementById(i1);
alert(a1);
}
</script>
</HEAD>
<BODY>
<div id= 'test1'>
<div id = 'test2'>
<input id = 'i1' type = 'text' name='i1' value='random'>
<input type='button' value="click me" onclick="test()">
</div>
</div>
</BODY>
Upvotes: 0
Views: 190
Reputation: 5752
change
var a1 = document.getElementById(i1);
to this
var a1 = document.getElementById(i1).value;
OR you can change
alert(a1);
to
alert(a1.value);
Upvotes: 0
Reputation: 2006
Example1
function test() {
var a1 = document.getElementById('i1').value;
alert(a1);
}
Example2
<input type='button' value="click me" onclick="test(document.getElementById('i1').value)">
function test(a1) {
alert(a1);
}
FULL HTML CODE
<HTML>
<HEAD>
<script>
function test()
{
var a1 = document.getElementById('i1').value;
alert(a1);
}
</script>
</HEAD>
<BODY>
<div id= 'test1'>
<div id = 'test2'>
<input id = 'i1' type = 'text' name='i1' value='random'>
<input type='button' value="click me" onclick="test()">
</div>
</div>
</BODY>
<HTML>
Upvotes: 0
Reputation: 1582
var a1 = document.getElementById(i1);
change to
var a1 = document.getElementById('i1').value;
Upvotes: 3
Reputation: 56501
You're missing quotes, also to get value you should use .value
.
function test() {
var a1 = document.getElementById("i1").value;
alert(a1);
}
Upvotes: 0